Search code examples
iosobjective-caudioplaybacklockscreen

Continue audio playback when iPhone is locked like iPod App


I need to continue the playback even when the user locks the phone. I've seen some solution over the internet, but none of them seem to work, such as:

AudioSessionSetActive(true);
    // Set up audio session, to prevent iPhone from deep sleeping, while playing sounds
    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
    AudioSessionSetProperty (
                             kAudioSessionProperty_AudioCategory,
                             sizeof (sessionCategory),
                             &sessionCategory
                             );

I'm inlcuding AVFoundation, AudioToolbox, and MediaPlayer.


Solution

  • I figured out how to do this.

    First of all, include these frameworks to your project: AudioToolbox, CoreAudio, MediaPlayer and AVFoundation. Import them all to the viewController where your player will be placed. After you allocated and started playing the audio, insert the following code:

    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
    AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (sessionCategory), &sessionCategory);
    AudioSessionSetActive(true);
    

    And finally, go to your app Info.plist file and add a row named UIBackgroundModes. The new row will be an array and will contain 1 item, the item 0. To this you just set the value as audio. And you're done! Enjoy you're background audio playing app!