Swift 同时播放更多次NSSound

Swift 同时播放更多次NSSound,swift,cocoa,nssound,Swift,Cocoa,Nssound,我需要在函数中插入一个代码,在调用时播放声音 问题是函数调用的速度比声音持续时间快,因此声音播放的次数比函数调用的次数少 function keyDownSound(){ NSSound(named: "tennis")?.play() } 问题是,NSSound仅在尚未播放时才开始播放。任何解决方法?问题的根源是init?(命名名称:String)返回相同名称的相同NSSound实例。您可以复制NSSound实例,然后同时播放多个声音: function keyDownSound(){

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

问题是函数调用的速度比声音持续时间快,因此声音播放的次数比函数调用的次数少

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

问题是,NSSound仅在尚未播放时才开始播放。任何解决方法?

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

function keyDownSound(){
    NSSound(named: "tennis")?.copy().play()
}
另一种方法-播放结束后再次启动声音。为此,您需要实现
sound(sound:NSSound,didFinishPlaying aBool:Bool)
delegate方法。例如:

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