我需要在函数中插入一个代码,当调用时播放声音。
问题在于该函数的调用速度比声音持续时间快,因此,声音的播放次数比函数调用的次数少。
function keyDownSound(){
NSSound(named: "tennis")?.play()
}
问题是 NSSound 仅在尚未播放时才开始播放。有什么想法可以解决吗?
问题的根源是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()
}