Ok, so my app plays videos, I want the sound to continue playing in the background. But when I hit the "Home" button the playback stops. I'm testing on iPhone 4s with iOS 5.0.1
What's working?
What's wrong?
What have I done:
Added the following code to app delegate's application:didFinishLaunchingWithOptions:
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
In my view controller I've implemented the methods to receive remote controls:
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//End recieving events
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
[self play:nil];
break;
case UIEventSubtypeRemoteControlPreviousTrack:
[self actionPlaybackPreviousItem];
break;
case UIEventSubtypeRemoteControlNextTrack:
[self actionPlaybackNextItem];
break;
default:
break;
}
}
}
How come everything works but, this?
Stack Overflow is becoming less and less responsive each time... Hopefully it's not so bad for everybody out there. I've found nothing to respond why is it that the video is paused after hitting the Home button, however, I've come with a workaround if it's of help to anyone:
Since the player is playing until the app goes to the background, i've created a timer, to check if the app was playing while it was in the foreground, if so, resume playback:
- (void)applicationWillResignActive:(UIApplication *)application
{
MainViewController* mainController=self.viewController;
playerWasPlaying=mainController.player.rate!=0;
}
-(void)resumePlayback {
MainViewController* mainController=self.viewController;
if (mainController.player.rate==0&&playerWasPlaying)
[mainController play:nil];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(resumePlayback) userInfo:nil repeats:NO];
}
Not the best option in my opinion, but for now it's working, with a little jump in the playback while it resumes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With