0

I am using the following code to keep playing audio when iPhone/iPod goes sleep or locked.

mv = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:@"http://myurl/myMusic.mp3"]];
mv.movieSourceType = MPMovieSourceTypeUnknown;
[self.view addSubview:mv.view];
[mv play];

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

By using this code my device is not going into sleep mode but what i want is, device should go in sleep mode but audio should not stop playing.
I have added Required background modesand App plays audio in my info.plist file.

Please suggest me where am I wrong? Why the device is not going into sleep mode/locked?

dandan78
  • 13,328
  • 13
  • 64
  • 78
iUser
  • 1,075
  • 3
  • 20
  • 49

2 Answers2

2

Use this code in viewdidload:

NSError *setCategoryErr = nil;
NSError *activationErr  = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
[[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

It is working fine for me.

WrightsCS
  • 50,551
  • 22
  • 134
  • 186
Vishal
  • 8,246
  • 6
  • 37
  • 52
1

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!

hope it helps. happy coding :)

Anshuk Garg
  • 1,540
  • 12
  • 14