在Swift中编写的SpriteKit iOS游戏中,播放非常短的声音(约0.5秒)会产生打produces(例如滞后)。在其他问题中,我读到我应该对声音进行prepareToPlay()
编码,这就是我所做的。
我什至使用了一个变量(soundReady
)在播放之前检查声音是否准备就绪。每当声音播放完毕时,我也会重新准备声音(audioPlayerDidFinishPlaying()
)。以下是代码的相关部分:
class GameScene: SKScene, AVAudioPlayerDelegate {
var splashSound = NSURL()
var audioPlayer = AVAudioPlayer()
var soundReady = false
override func didMoveToView(view: SKView) {
let path = NSBundle.mainBundle().pathForResource("plopSound", ofType: "m4a")
splashSound = NSURL(fileURLWithPath: path)
audioPlayer = AVAudioPlayer(contentsOfURL: splashSound, error: nil)
audioPlayer.delegate = self
soundReady = audioPlayer.prepareToPlay()
}
func playSound(){
if(soundReady){
audioPlayer.play()
soundReady = false
}
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool){
//Prepare to play after Sound finished playing
soundReady = audioPlayer.prepareToPlay()
}
}
我不知道我在哪里犯了错误。我感觉我已经尝试了所有方法(包括但不限于:仅准备一次,在播放后立即准备,不使用变量,而只是prepareToPlay())。
附加信息:
最佳答案
我遇到了同样的问题,并在backgroundQueue中播放了声音。
这是一个很好的示例:https://stackoverflow.com/a/25070476/586204。
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
audioPlayer.play()
})