同时播放NSSound更多次

时间:2016-03-13 22:28:56

标签: swift cocoa nssound

我需要在函数中插入一个代码,当调用时播放声音。

问题是该功能被称为比声音持续时间更快,因此,声音播放次数少于函数调用。

function keyDownSound(){
   NSSound(named: "tennis")?.play()
}

问题是NSSound只有在尚未播放时才开始播放。有什么想法要修复吗?

1 个答案:

答案 0 :(得分:1)

问题的根源是init?(named name: String)为同一个名称返回相同的NSSound个实例。您可以复制NSSound实例,然后会同时播放几个声音:

function keyDownSound(){
    NSSound(named: "tennis")?.copy().play()
}

替代方式 - 完成播放后再次开始播放声音。为此,您需要实现sound(sound: NSSound, didFinishPlaying aBool: Bool)委托方法。例如:

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()
}