Search code examples
iossprite-kitavaudioplayerskactionskscene

AVAudioPlayer and performance issue in SpriteKit game


I have problem with AVAudioPlayer and playing the short sounds in my spritekit game. I have quite dynamic game scene and when the user tap into particular element I want to play simple "beep" sound, but I notice that performing sound using AVAudioPlayer cause significant performance issue.

My audio files are in .mp3 format.

Also I have tried SKAction method (playSoundFileNamed) to perform sound and everything looks almost the same, I noticed the same performance issue.

My question is what is the best practice to perform sound in SpriteKit.

PS: I tried to find WWDC Adventure spritekit sample code to check how they resolve problem with playing sounds, but unfortunately sample code is no longer available.


Solution

  • 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