Search code examples
iosiphoneaudiostreamer

How to resume audio when iphone is locked/unlocked and the application was in background


This is the case: I made an app using the Audio Streamer library that reads an audio file from a remote server, but I find a problem only if I do this:

  1. Launch the app
  2. Start a Podcast (audio stream)
  3. Pause it
  4. Put the app on the background (home button)
  5. Lock the phone
  6. Unlock it
  7. Reactivate the app

And only then, my stream will be stopped. I am attempting to reach the paused state, but could not get it done.

This happens only if I put the app in background, if not and I lock/unlock the iPhone, everything is alright again. If I pause the stream then put the app into background (Home button) and then the app is resigned from background-state, everything is OK.

So, this problem only occurs if these two things happen: App sent to background + Lock/unlock the iphone


Solution

  • does it use AVAudioPlayer under the hood? If so you need to handle the AVAudioPlayerDelegate protocols:

    - (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
    

    and

    - (void) audioPlayerEndInterruption: (AVAudioPlayer *) player {
    

    .. methods. Essentially use the first to store the fact that the AVAudioPlayer was stopped due to an interruption, and the second to start it off again. Fiddly, but unfortunately neccessary.

    Here's a link https://developer.apple.com/documentation/avfoundation/avaudioplayerdelegate