简体   繁体   中英

continue playing audio when iphone/device goes sleep or locked

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?

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.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM