开发者

AVAudioPlayer lag when calling play

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 pla开发者_如何学Pythonyer to lag on the first play?

Thanks.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜