尽管在 Swift 中使用 prepareToPlay() ,AVAudioPlayer 仍会产生延迟 [英] AVAudioPlayer produces lag despite prepareToPlay() in Swift
问题描述
在我用 Swift 编程的 SpriteKit iOS 游戏中,播放很短的声音(~0.5 秒)会产生打嗝(如延迟).在其他问题中,我读到我应该 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屋!