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?

Answered by John K. in 299329022

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.

Accepted Answer

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.

Hi, I have preparetoplay function called as soon as init is created of the sound file.

I play it later.

95% of times, the sounds are working correctly.

But when sometimes, i use a lots of other competitor apps, games and return to my own app, i hear the sounds becoming glitchy in my app. And as soon as i press lock button to use siri and return back instantly, the sounds start working correctly.

Similarly, this happens when we lock the device and come back to the app, which also rectifies the issue.

I tried serialqueues, global sync ( because the sounds are coming rapidly one after another), reduced CPU/memory loads drastically, tried recreating audio files in interruptions, appdidbecomeactive.

Am using playback audio category for my app. Though when removed the audio category setup, this issue also happens on default setup of audio which ios provides for the app. Tried removing mixwithothers, didnt resolve.

Tried almost everything but i cant resolve this issue.

Even replaced the library of audio with a low latency one. that low latency sounds are working fine but taking lots of memory.

The Avaudioplayer setup keeps the memory not too much.

What could be the reason for this audio getting correct on opening siri and back and also on lock screen lock and unlock?

Why Does AVAudioPlayer Cause Lag?
 
 
Q