我正在创建一个用户使用喷气背包控制角色的游戏。当喷气背包与钻石相交时,我将钻石添加到它们的总数中,然后发出声音。然而,声音使游戏暂停十分之一秒左右,并扰乱了流程。这是我正在使用的代码:
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。非常感谢任何帮助!
答案 0 :(得分:0)
通常情况下,我首先在我的游戏中使用SKAction.playSoundWithFile
,但这个有限制,没有音量设置。
所以,通过这个扩展你可以解决这个问题:
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))