在Swift中编写的SpriteKit iOS游戏中,播放非常短的声音(~0.5s)会产生打嗝(如滞后).在其他问题中,我读到了我应该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()
} …Run Code Online (Sandbox Code Playgroud)