start playing audio from a background task via AVAudioPlayer in Xcode

前端 未结 5 1055
小鲜肉
小鲜肉 2021-02-03 14:46

I am trying to start playing a sound from a background task via an AVAudioPlayer that is instantiated then, so here\'s what I\'ve got.

For readability I cut out all user

5条回答
  •  無奈伤痛
    2021-02-03 15:18

    From what I've learned after writing an player App, it seems that you can not start playing audio when your App is already in background for longer than X seconds, even if you have configured everything right.

    To fix it, you have to use background task wisely. The most important thing is that you must NOT call endBackgroundTask immediately after playSoundFile. Delay it for about 5-10 seconds.

    Here is how I managed doing it for iOS6 and iOS7.

    1, Add audio UIBackgroundModes in plist.

    2, Set audio session category:

    3, Create an AVQueuePlayer in the main thread and enqueue an audio asset before the App enter background.

    *For continues playing in background (like playing a playlist)*

    4, Make sure the audio queue in AVQueuePlayer never become empty, otherwise your App will be suspended when it finishes playing the last asset.

    5, If 5 seconds is not enough for you to get the next asset you can employ background task to delay the suspend. When the asset is ready you should call endBackgroundTask after 10 seconds.

提交回复
热议问题