AVAudioPlayer and performance issue in SpriteKit game

梦想与她 提交于 2019-12-01 12:29:08

You are probably getting lag because you are not preloading your sound files and therefore get some lag/delay when creating/playing them. The best practice is to usually preload your audio files at app launch so that they are ready to play immediately.

So for AVPlayers just set them all up at app launch rather than just before playing them. Than when you want to play the music you just play the AVPlayer.

myAVPlayer1.play()

In regards to SKAction.play... its the same issue. You will need to create a reference to your action rather than calling it directly

So in your gameScene above DidMoveToView you create your sound properties

class GameScene: SKScene {

     let sound1 = SKAction.playSoundFileNamed("Test", waitForCompletion: false)

     ....
}

and than in your game at the correct spot you run it

runAction(sound1)

This way there should be no lag because the sound is already preloaded.

Hope this helps

I think you must simply review who run this action. If your sprite is involved in other actions, or some context animations, you can try to launch your sound from the SKNode who host your sprite. The best way is always to use reasonable mp3 dimensions..

P.S. : Usually I preefer to use this extension to control also the volume:

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.play()
        }

        if(waitForCompletion){
            let waitAction = SKAction.waitForDuration(player.duration)
            let groupAction: SKAction = SKAction.group([playAction, waitAction])
            return groupAction
        }

        return playAction
    }
}

About performance, it is preferable to convert your audio files into .Wav instead of .mp3 The processor then hasn't to uncompress the file before to use it.

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