播放 AVAudioPlayer 时游戏卡顿 [英] Game lagging when AVAudioPlayer plays
问题描述
我正在创建一个用户使用喷气背包控制角色的游戏.当喷气背包与钻石相交时,我将钻石加到它们的总数中,然后播放声音.但是,声音会使游戏暂停十分之一秒左右并打乱流程.这是我正在使用的代码:
I'm creating a game where the user controls a character with a jetpack. When the jetpack intersects a diamond, I add the diamond to their total and then play a sound. However, the sound makes the game pause for a tenth of a second or so and disrupts the flow. This is the code I'm using:
var diamondSound = NSBundle.mainBundle().URLForResource("diamondCollect", withExtension: "wav")!
var diamondPlayer = AVAudioPlayer?()
class GameScene: SKScene{
override func didMoveToView(view: SKView) {
do {
diamondPlayer = try AVAudioPlayer(contentsOfURL: diamondSound)
guard let player = diamondPlayer else { return }
player.prepareToPlay()
} catch let error as NSError {
print(error.description)
}
}
然后:
override func update(currentTime: CFTimeInterval) {
if character.intersectsNode(diamond){
diamondPlayer?.play()
addDiamond()
diamond.removeFromParent()
}
}
如果这很重要,我也在使用 Sprite Kit.非常感谢任何帮助!
Also I am using Sprite Kit if that matters. Any help is greatly appreciated!
推荐答案
通常我更喜欢在我的游戏中使用SKAction.playSoundWithFile
但是这个有一个限制,没有音量设置.所以,有了这个扩展,你就可以解决这个不足:
Usually, I prefeer to use SKAction.playSoundWithFile
in my games but this one have a limitation, there is no volume setting.
So, whit this extension you can solve this lack:
public extension SKAction {
public class func playSoundFileNamed(fileName: String, atVolume: Float, waitForCompletion: Bool) -> SKAction {
let nameOnly = (fileName as NSString).stringByDeletingPathExtension
let fileExt = (fileName as NSString).pathExtension
let soundPath = NSBundle.mainBundle().URLForResource(nameOnly, withExtension: fileExt)
var player: AVAudioPlayer! = AVAudioPlayer()
do { player = try AVAudioPlayer(contentsOfURL: soundPath!, fileTypeHint: nil) }
catch let error as NSError { print(error.description) }
player.volume = atVolume
let playAction: SKAction = SKAction.runBlock { () -> Void in
player.prepareToPlay()
player.play()
}
if(waitForCompletion){
let waitAction = SKAction.waitForDuration(player.duration)
let groupAction: SKAction = SKAction.group([playAction, waitAction])
return groupAction
}
return playAction
}
}
用法:
self.runAction(SKAction.playSoundFileNamed("diamondCollect.wav", atVolume:0.5, waitForCompletion: true))
这篇关于播放 AVAudioPlayer 时游戏卡顿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!