6
votes

I have set up an AVAudioPlayer object in viewDidLoad, as per the Apple guidelines, calling prepareToPlay as the last line in viewDidLoad (i have tried in awakeFromNib also).

When i press my play button, there is a pause, as it would appear to load the file, then it plays.

In audioPlayerDidFinishPlaying, i reload the player with a different sound, and when clicking play for a second time, the file plays instantly.

What would cause the player to lag on the first play?

Thanks.

3

3 Answers

0
votes

The delay is due to AVAudioPlayer being initialised. Please see this answer.

0
votes

The audio system runs on several asynchronous software processes (audio units, OS drivers, etc.) and hardware systems (DMA, DACs, audio amp power supplies, etc.) that never really all completely finish initialization until some sound is actually played all the way out the speakers or earphones.

Here's one method to do that: Create a sound file containing a half second of silence. On app start up, while your app and view controller are still loading, use AVAudioPlayer to play this file of silence. Now when your view finishes loading, AVAudioPlayer should be ready to play subsequent non-silent sounds much faster, since some audio (silence) has already already gone all the way out to the speakers.

-1
votes

What kind of sound are you playing? Alerts, something longer? If alerts, I did go this way and it's much better with lags ...

  • create system sound with AudioServicesCreateSystemSoundID
  • play system sound with AudioServicesPlaySystemSound
  • dispose system sound with AudioServicesDisposeSystemSoundID

... you only need to store SystemSoundID for each sound you would like to play.