1

How can I continue an audio playback in iPhone when it auto-locks or the user locks the phone?

I already tried

session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:NULL];

but that doesn't seem to work.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
gabriel_vincent
  • 1,230
  • 3
  • 16
  • 35

2 Answers2

1

I finally 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!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
gabriel_vincent
  • 1,230
  • 3
  • 16
  • 35
0

This link should help.

You need to prevent the app from entering a deep sleep mode:

UInt32 category = kAudioSessionCategory_MediaPlayback;
OSStatus result = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
                                                                            sizeof(category), &category);

if (result){
    DebugLog(@"ERROR SETTING AUDIO CATEGORY!\n");
}

result = AudioSessionSetActive(true);
if (result) {
    DebugLog(@"ERROR SETTING AUDIO SESSION ACTIVE!\n");
}
Community
  • 1
  • 1
dgund
  • 3,459
  • 4
  • 39
  • 64
  • Thanks for the answer! But when I try to compile the code I get some errors and warning I don't quite understand. FIrst, XCode thinks `kAudioSessionCategory_MediaPlayback` was an attempt to write `AVAudioSessionCategoryPlayback`. Then I get an error of use of undeclared identifier "kAudioSessionCategory_MediaPlayback". And a warning saying "implicit declaration of function `AudioSessionSetProperty` is invalid in C99. – gabriel_vincent Jan 19 '12 at 02:38