Reputation: 1075
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 modes
and 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?
Upvotes: 0
Views: 2531
Reputation: 8256
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.
Upvotes: 2
Reputation: 1540
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 :)
Upvotes: 1