Game lagging when AVAudioPlayer plays

与世无争的帅哥 提交于 2019-12-04 06:18:22

问题


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)
            }
       }

And then later:

    override func update(currentTime: CFTimeInterval) {

        if character.intersectsNode(diamond){
            diamondPlayer?.play()
            addDiamond()
            diamond.removeFromParent()
        }

    }

Also I am using Sprite Kit if that matters. Any help is greatly appreciated!


回答1:


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
  }
}

Usage:

self.runAction(SKAction.playSoundFileNamed("diamondCollect.wav", atVolume:0.5, waitForCompletion: true))


来源:https://stackoverflow.com/questions/38402462/game-lagging-when-avaudioplayer-plays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!