I am implementing some video into my iPad app and its works fine. But the issue I am running into is that when I leave the view to navigate somewhere else the video audio keeps playing in the background. Is there a way to completely stop the video and remove it from the view before closing the view?
I tried:
[moviePlayerController stop]; – But that does not seem to stop the movie it just crashes the app.
[moviePlayerController.view removeFromSuperview]; – That removes the video from the view but does not stop the audio.
This is what I have for the code:
- (IBAction)PlayMediaButton:(id)sender
{
[moviePlayerController stop];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
NSString *movpath = [[NSBundle mainBundle] pathForResource:@"albert" ofType:@"mp4"];
MPMoviePlayerViewController* mpviewController = [[MPMoviePlayerViewController alloc]
initWithContentURL:[NSURL fileURLWithPath:movpath]];
if ([[NSFileManager defaultManager] fileExistsAtPath:movpath]) //Does file exist?
{
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:movpath]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlaybackComplete:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayerController];
moviePlayerController.view.frame = CGRectMake(38, 37, 986, 618);
[self.view addSubview:moviePlayerController.view];
[moviePlayerController play];
if ([moviePlayerController respondsToSelector:@selector(setAllowsAirPlay:)]) //Allow airplay if availabe
[moviePlayerController setAllowsAirPlay:YES];
[moviePlayerController play];
}
}
- (void)moviePlaybackComplete:(NSNotification *)notification
{
MPMoviePlayerController *moviePlayerController = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayerController];
[moviePlayerController.view removeFromSuperview];
[moviePlayerController release];
}
If I’m following you correctly, you should stop the movie player controller in
-viewWillDisappear:.Edit Just noticed that you’re creating a
MPMoviePlayerViewControllerinstead of anMPMoviePlayerController. The former is meant to be displayed modally since it as a subclass ofUIViewController. This explains the crash becauseMPMoviePlayerViewControllerdoesn’t respond to a-stopmessage. So either, displaymoviePlayerControllerwith-presentModalViewController:animated:or change it’s type toMPMoviePlayerControllerand add it to your view as you are doing now.