Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play NSSound more times, simultaneously

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?

like image 483
Alessandro Avatar asked Sep 16 '25 16:09

Alessandro


1 Answers

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()
}
like image 103
Borys Verebskyi Avatar answered Sep 19 '25 08:09

Borys Verebskyi