Why Does AVAudioPlayer Cause Lag?

Whenever I call the following my app gets laggy.

func playSound() {
     if soundsOn {
          audioPlayer.prepareToPlay()
          audioPlayer.play()
     }
}


I've already done this in the didMove(to view: SKView):

do {
     audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "ButtonPressSound", ofType: "wav")!))
}
catch {
     print(error)
}


The sound plays, but like I mentioned, the app gets laggy; movement of SKNodes gets choppy.


Why does this happen? Is there any way to fix this?

Accepted Reply

I've done some more research and I haven't found a fix for lag when using AVAudioPlayer, but I have found out that it's better to use the AudioServicesCreateSound and AudioServicesPlaySound method of playing sound.

Replies

I've done some more research and I haven't found a fix for lag when using AVAudioPlayer, but I have found out that it's better to use the AudioServicesCreateSound and AudioServicesPlaySound method of playing sound.

:John,


Try moving "audioPlayer.prepareToPlay()" to right after:

audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "ButtonPressSound", ofType: "wav")!))


prepareToPlay Documentation:

Calling this method preloads buffers and acquires the audio hardware needed for playback, which minimizes the lag between calling the

play()
method and the start of sound output.


You should call prepareToPlay before the user needs it to play.