I need to insert a code, in function, that when called play a sound.
The problem is that the function is called faster than sound duration and so, the sound is played less times than function calls.
function keyDownSound(){
NSSound(named: "tennis")?.play()
}
The problem is that NSSound starts playing only if isn't already played. Any ideas to fix?
Source of problem is that init?(named name: String)
return same NSSound
instance for same name. You can copy NSSound
instance, then several sounds will play simultaneously:
function keyDownSound(){
NSSound(named: "tennis")?.copy().play()
}
Alternative way - start sound again after finish playing. For that you need to implement sound(sound: NSSound, didFinishPlaying aBool: Bool)
delegate method. For example:
var sound: NSSound?
var playCount: UInt = 0
func playSoundIfNeeded() {
if playCount > 0 {
if sound == nil {
sound = NSSound(named: "Blow")!
sound?.delegate = self
}
if sound?.playing == false {
playCount -= 1
sound?.play()
}
}
}
func keyDownSound() {
playCount += 1
playSoundIfNeeded()
}
func sound(sound: NSSound, didFinishPlaying aBool: Bool) {
playSoundIfNeeded()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With