Cancel a Movie before it begins playing - iphone

I'm streaming video to the iPhone and don't like the way MPMoviePlayerController handles things at the beginning. I noticed that when you click on the row to select a particular movie the app just sits there until it is loaded sufficiently to play it. So I popped in a UIImageView with a loading image and a nice spinner to keep the user informed.
I think they should have the option to cancel the play back of the movie if they get tired of waiting. So I've got a cancel button with a background image.
UIButton *cancel;
UIImage *cancelImage = [UIImage imageNamed:#"cancel.png"];
cancel = [UIButton buttonWithType:UIButtonTypeCustom];
cancel.frame = CGRectMake(0,0, cancelImage.size.width, cancelImage.size.height);
cancel.center = CGPointMake(35, 20);
[cancel setImage:cancelImage forState:UIControlStateNormal];
[cancel addTarget:self action:#selector(cancelMovie) forControlEvents:UIControlEventTouchUpInside];
[moviePreviewView addSubview:cancel];
But I'm not sure what to put in the cancelMovie method. I've tried duplicating what I have in the moviePlayBackDidFinish call back method but it crashes rather spectacularly.
I also tried:
-(void)cancelMovie {
[theMovie.view removeFromSuperview];
[theMovie release];
}
But that doesn't do anything good either. I was thinking I could call the moviePlayBackDidFinish directly but I don't think you can call a notification method directly.
Your thoughts?

I hate answering my own question but since this question only had 7 views it couldn't be that important I suppose. Perhaps I shouldn't post them in the middle of the night... no one sees them when you do.
Anyway, I didn't find a good solution to this problem... just a hack.
In the cancel method I told the moviePlayer to load a different, one second movie that is a the same photo I used in the previewImage. When that 'movie' finishes it then proceeds to call the MPMoviePlayerPlaybackDidFinishNotification and cleans up and returns the user back where they were.
-(void)cancelMovie
{
cancelURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"cancel" ofType:#"m4v"]];
[theMovie setContentURL:cancelURL];
[theMovie setControlStyle:MPMovieControlStyleFullscreen];
[theMovie setFullscreen:YES];
// for some reason ... this is neccessary
[theMovie prepareToPlay];
// Register that the load state changed (movie is ready)
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerLoadStateChanged:)
name:MPMoviePlayerLoadStateDidChangeNotification
object:theMovie];
// Register for the PlayBackDidFinish (movie is finished)
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:theMovie];
}
Not good... but it works.

#Michael solution works.
There could be improvement that there is no need to play cancel video. Instead, you can directly call the MPMoviePlayerPlaybackDidFinishNotification directly.
[self moviePlayBackDidFinish:nil];
First i implemented #Michael's idea, but eventually, i succeeded without playing next video.

-(void)cancelMovie
{
if (_mediaPlayer){
[_mediaPlayer stop];
_mediaPlayer.initialPlaybackTime = -1.0;
_mediaPlayer.contentURL = nil;
[_mediaPlayer prepareToPlay];
}
}

Related

How to play another video in the same MPMoviePlayerController?

*I'm creating an iPhone app where we can watch videos...
I,ve been making my own controls so I want to implement the next, back buttons, I can show theme so for the UI everything is ok the problem is to restart the MoviePlayer with another content...
Any idea???
I could use the same configuration when the playback did finish, I mean... If the video ends playing to start playing another one...
I've tried to set contentUrl but it trows an exception:
2012-04-17 11:37:41.198 NexTest2[8218:11f03] *** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan 11.5]'
viewController.m
- (void)viewDidLoad{
[super viewDidLoad];
fileURL = [NSURL URLWithString:urlString];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
moviePlayerController.controlStyle = MPMovieControlStyleNone;
[moviePlayerController setShouldAutoplay:YES];
[self addObservers];
/* Inset the movie frame in the parent view frame. */
CGRect viewInsetRect = CGRectInset ([self.view bounds],0.0, 0.0 );
[[moviePlayerController view] setFrame: viewInsetRect ];
[self.view addSubview:moviePlayerController.view];
[self resizeControlViews];
}
then in resizeControlViews I have this, cause I'm using these two views like controls:
-(void)resizeControlViews{
CGRect barFrame = self.controlBarView.frame;
barFrame.origin.x = round((moviePlayerController.view.frame.size.width - barFrame.size.width) / 2.0);
barFrame.origin.y = round((moviePlayerController.view.frame.size.height - barFrame.size.height)/10.0);
self.controlBarView.frame = barFrame;
[moviePlayerController.view addSubview:controlBarView];
CGRect playFrame = self.controlPlaybackView.frame;
playFrame.origin.x = round((moviePlayerController.view.frame.size.width - playFrame.size.width) / 2.0);
playFrame.origin.y = round((moviePlayerController.view.frame.size.height - playFrame.size.height)/1.1);
self.controlPlaybackView.frame = playFrame;
[moviePlayerController.view addSubview:controlPlaybackView];
}
Here everything is working fine, in one of these views there is a slider who controls the seeking, and in the other one are the play, next and back buttons.
I think maybe the problem is whit the UI components of these views...
I've added these observers to control the playback:
//Add the observers to the player
-(void)addObservers{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playbackStarted:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(setDurationLabel:) name:MPMovieDurationAvailableNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyWindowChanged:) name:UIWindowDidBecomeKeyNotification object:nil];
}
so to handle when the player is playing I use the MPMoviePlayerPlaybackStateDidChangeNotification with this selector:
//called when the playback state changes of state
- (void)playbackStarted:(NSNotification*)notification {
MPMoviePlayerController *player = notification.object;
if (player.playbackState == MPMoviePlaybackStatePlaying) {
[self timerRunning];
}
}
and if the player is "playing" I monitor it with this method:
-(void)timerRunning{
self.currentTime.text = [self floatToStringTime:(moviePlayerController.currentPlaybackTime)];
self.timeBar.value = moviePlayerController.currentPlaybackTime / moviePlayerController.duration;
if (moviePlayerController.playbackState == MPMoviePlaybackStatePlaying) {
[self performSelector:#selector(timerRunning) withObject:nil afterDelay:0.5];
}
}
so Maybe here is the issue... but with a single video it works perfectly...
I've four where the mistake is... is while i'm monitoring in the line to set the value to the slider, but I really don't know why, I think it is cause when another video or stoping video it is still executed so the player has not duration or current playback what trows this exception... how could I to solve it... here is the mistake... maybe moving this code to another part...
self.timeBar.value = moviePlayerController.currentPlaybackTime / moviePlayerController.duration;
Check your UI related code. You most likely are not properly checking the player status before getting and using content related properties from it.
Well finally it works fine... the setCurrentContentUrl works fine, the problem was my code so I solved it... I just validate that duration was different to 0...
Now I have a player with full custom controls :) cool :)
-(void)timerRunning{
if (moviePlayerController.playbackState == MPMoviePlaybackStatePlaying) {
self.currentTime.text = [self floatToStringTime:(moviePlayerController.currentPlaybackTime)];
if (moviePlayerController.duration != 0) {
self.timeBar.value = moviePlayerController.currentPlaybackTime / moviePlayerController.duration;
}
[self performSelector:#selector(timerRunning) withObject:nil afterDelay:0.5];
}
}
Thank you anyways

MPMoviePlayerController plays after canceling in 3.1.2

I have encountered a problem with the MPMoviePlayerController in 3.1.2.
If I cancel the player while it is still loading, the player closes. However, the video starts playing a few moments later in the background. The only ways to stop it are to play another video or close the app. This seems to work fine in 3.2+.
Here's what I'm doing:
- (void)loadMoviePlayer
{
// Register to receive a notification when the movie has finished playing.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
if ([NSClassFromString(#"MPMoviePlayerController") instancesRespondToSelector:#selector(view)])
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
// running iOS 3.2 or better
MPMoviePlayerViewController *moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:#"http://www.mysite.com/myvideo.m3u8"]];
[moviePlayer.view setBackgroundColor:[UIColor blackColor]];
[moviePlayer.moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
// [moviePlayer.moviePlayer setControlStyle:MPMovieControlStyleNone];
[self presentMoviePlayerViewControllerAnimated:moviePlayer];
[moviePlayer.moviePlayer prepareToPlay];
[moviePlayer.moviePlayer play];
#endif
}
else
{
MPMoviePlayerController *mMPPlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:#"http://www.mysite.com/myvideo.m3u8"]];
mMPPlayer.scalingMode=MPMovieScalingModeFill;
mMPPlayer.backgroundColor=[UIColor blackColor];
[mMPPlayer play];
}
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
[[UIApplication sharedApplication] setStatusBarHidden:NO];
// Remove observer
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
[self dismissModalViewControllerAnimated:YES];
}
I added moviePlayBackDidFinish this morning. It gets called when I hit cancel, but dismissModalViewControllerAnimated doesn't seem to do anything. I also tried removeFromSuperView, but my player will not respond.
So, how can I make sure the player does not play after hitting "cancel"?
Thanks in advance.
You may have come across an old bug in MPMoviePlayerController. Back in the days, we actually had to play an almost empty (black, silence) M4V after playing proper content to be sure the player does not attempt to continue playback in the background when stopping at certain stages. That bug manifests in audible sound but no picture of the aborted/stopped video.
There are however a few more things worth trying when stopping (assuming your instance of MPMoviePlayerController is called moviePlayer);
set the current playback position to the complete movie duration moviePlayer.currentPlaybackTime = moviePlayer.duration;
send another stop within your notification handler [moviePlayer stop];
In my case, I found that setting the following line would eventually stop the movie player from playing:
moviePlayer.contentURL = nil;
(with moviePlayer your instance of MPMoviePlayerController).

Why does MPMoviePlayerController prevent resumption of audio after the movie ends?

I have a class that plays a repeating background music loop with an AVAudioPlayer, and on specific occasion, plays a full-screen video with its own sound track using MPMoviePlayerController. In order to to have only one track at a time, I stop the background music before launching the video:
-(void)startVideo{
[backgroundMusic stop];
MPMoviePlayerViewController *mp = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"videofile" ofType:#"m4v"]]];
[self presentMoviePlayerViewControllerAnimated:mp];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(videoOver) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[mp.moviePlayer play];
[mp release];
}
-(void)videoOver{
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
if(![backgroundMusic play]){
NSLog(#"bad: can't resume bg music!");
[backgroundMusic release];
backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"videofile" ofType:#"m4v"]] error:NULL];
backgroundMusic.delegate = self;
backgroundMusic.numberOfLoops = -1;
[backgroundMusic play];
}
}
The resumption worked fine without recreating the AVAudioPlayer object (i.e. the play method returned YES) on analogous code on os versions up to and including 3.2. But on iOS4, the play method always returns NO, and has to recreate the object. Why is that, and can I get to resume the background track properly (I have cases where the solution used above is unacceptable.)?
Figured this out. It turns out that in iOS 3.2 and above, when a video finishes playing, it goes into MPMoviePlaybackStatePaused state rather than MPMoviePlaybackStateStopped, and in order to make it release the hardware, you have to explicitly call the stop method on MPMoviePlayerController after it finishes playing before trying to resume AVAudioPlayer.

MPMoviePlayerController worked fine up to iOS 4.0 now just plays sound, no video

The code below is more or less taken from the example MPMoviePlayerController sample code. In an app I wrote last year, it used to play videos fullscreen without an issue. Since iOS 4.0, there's just audio in the background. It's like the movie player doesn't have a view or the view is behind my app. I can still interact with my app, even 'start' a new video (audio only).
It's like the movie player now needs a view, but I don't see any way of supplying this in the API or the sample code (which does seem to be a version or two behind.
I load my videos from a URL and if I type these into Safari, they play just fine.
Here's the relevant code fragments, for what it's worth:
- (void)playMovieUrl:(NSURL*)url
delegate:(id)delegate
callbackSelector:(SEL)selector
{
#try {
movieFinishedCallbackDelegate = delegate;
movieFinishedCallbackSelector = selector;
movieURL = url;
MPMoviePlayerController* theMovie=[[MPMoviePlayerController alloc] initWithContentURL:url];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(myMovieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:theMovie];
[theMovie play];
}
#catch (NSException * e) {
return;
}
}
// When the movie is done,release the controller.
-(void)myMovieFinishedCallback:(NSNotification*)aNotification
{
MPMoviePlayerController* theMovie=[aNotification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:theMovie];
[theMovie release];
[movieURL release];
[movieFinishedCallbackDelegate performSelector:movieFinishedCallbackSelector];
}
You probably need to present theMovie:
[self presentMoviePlayerViewControllerAnimated:theMovie];
And change to:
MPMoviePlayerViewController
in ios 3.2 letter use MPMoviePlayerViewController. it behave like a modelViewcontroller

Overlay View Problem When Playing Two Different Movies in Sequence

I'm trying to play two videos using the MPMoviePlayerController class and allow the user to switch between the two videos by swiping their finger across the screen. Everything works great for the first movie. The overlay view correctly detects the swipe and starts the next movie playing.
Unfortunately things don't work so well with the second movie. I'm not sure what's happening, but the overlay view does not actually seem to be on top of the movie player and is certainly not responding to touch events. In fact, double tapping the screen while the second movie is playing zooms the movie in and out, so touches seem to be going to the MPMoviePlayerController.
I've tried a number of different approaches here, but none of them work. Here is the current version of the code:
- (void)allocateMoviePlayerForCurrentVideo
{
// Create a movie player for the first video in the playlist
NSURL *url = [videoURLs objectAtIndex:nowPlayingVideoIndex];
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
moviePlayer.movieControlMode = MPMovieControlModeHidden;
moviePlayer.backgroundColor = [UIColor blackColor];
// Register for the movie preload complete notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePreloadComplete:)
name:MPMoviePlayerContentPreloadDidFinishNotification
object:nil];
// Register for the playback did finish notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(movieDidFinishPlaying:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
}
The code which handles the MPMoviePlayerContentPreloadDidFinishNotification starts the movie playing and adds the overlay view:
- (void)moviePreloadComplete:(NSNotification *)notification
{
// Remove this object from observing the preload complete notification
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerContentPreloadDidFinishNotification
object:nil];
// Start playing the current movie
[moviePlayer play];
// Add the overlay view to the movie player
UIWindow *moviePlayerWindow= [[[UIApplication sharedApplication] windows] objectAtIndex:1];
overlayView = [[GGDMovieOverlayView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
overlayView.backgroundColor = [UIColor clearColor];
[moviePlayerWindow addSubview:overlayView];
[moviePlayerWindow bringSubviewToFront:overlayView];
// Register for swipe notifications from the overlay view
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(handleMoviePlayerSwipeNotification:)
name:GGDMoviePlayerSwipeNotification
object:nil];
}
And finally, here's the routine which handles the swipe notification:
- (void)handleMoviePlayerSwipeNotification:(NSNotification *)notification
{
// Stop the current movie player and release it
[moviePlayer stop];
[moviePlayer release];
moviePlayer = nil;
// Remove the overlay view from its superview
[overlayView removeFromSuperview];
// Advance to the next movie, treating the array of video URLs as a circular array
if ( ++nowPlayingVideoIndex == [videoURLs count] ) {
nowPlayingVideoIndex = 0;
}
[self allocateMoviePlayerForCurrentVideo];
}
I fear there's something obvious I'm missing, but this has been driving me crazy for a while now. I very much appreciate any help!
Thanks,
Adam
I just went through this myself and I can explain the issue and a slightly better workaround.
The problem with running the next movie in sequence is that the notification that you get when the movie has finished playing occurs before the current movie player window has been removed from the view. This is an issue because (as per the Apple example) the only way to get the movie player window is to grab the top window on the stack (or the key window). But if you try to use this technique immediately you'll get the old movie player window that is fading out, not the new one that is going to start. (As an aside - frankly, the Apple example is an illustration that there really isn't a proper way to get the movie window at all.. their example is terrible and is probably a race condition to begin with unless somehow the play method blocks until the window is actually on the stack).
Anyway, rather than an arbitrary delay, what I did is to tag the player window at the time that it is first created e.g.
UIWindow *moviePlayerWindow = [[UIApplication sharedApplication] keyWindow];
moviePlayerWindow.tag = MY_MOVIE_WINDOW_TAG; // this is just an int
and then in the moviePlaybackDidFinish method I call a waitForMovieWindowToExit method that looks for that tagged window. If it's still there then I use a timer to check again in 0.1 seconds. When it finally disappears I play the next sequence.
So, it's still a mess and still using a timer, but at least you are guaranteed to play the next movie within 0.1 second (or whatever) of the next possible time and it won't break if the system is a little slow, etc.
If anyone wants more code I can post it.
Fixed by using a NSTimer to add the overlay view after a delay to make sure the movie has started playing.
Thanks,
Adam