尽管在Swift中使用prepareToPlay(),AVAudioPlayer仍会产生延迟 [英] AVAudioPlayer produces lag despite prepareToPlay() in Swift
问题描述
播放非常短的声音(~0.5s)会在Swift中编写的SpriteKit iOS游戏中产生打嗝(如滞后)。在其他问题中,我读到我应该 prepareToPlay()
声音,我做了。
Playing a very short sound (~0.5s) produces a hiccup (like a lag) in my SpriteKit iOS game programmed in Swift. In other questions, I read that I should prepareToPlay()
the sound, which I did.
我甚至使用变量( soundReady
)来检查声音是否在播放前准备好了。我也会在完成播放时重新准备声音( audioPlayerDidFinishPlaying()
)。以下是代码的相关部分:
I even used a variable (soundReady
) to check if the sound is prepared before playing it. I also re-prepare the sound whenever it is finished playing (audioPlayerDidFinishPlaying()
). Here are the relevant parts of the code:
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())。
I have no idea where I've gone wrong on this one. I feel like I have tried everything (including, but not limited to: only preparing once, preparing right after playing, not using a variable, but just prepareToPlay()).
其他信息:
- 声音无延迟播放。
- 播放声音的速度有多快最后一次完成似乎没有影响滞后。
推荐答案
我遇到了同样的问题并在backgroundQueue中播放声音。
I ran into this same problem and played the sound in the backgroundQueue.
这是一个很好的例子: https ://stackoverflow.com/a/25070476/586204 。
This is a good example: https://stackoverflow.com/a/25070476/586204.
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
audioPlayer.play()
})
这篇关于尽管在Swift中使用prepareToPlay(),AVAudioPlayer仍会产生延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!