MPMoviePlayerController playback terminates before

2019-08-26 20:05发布

问题:

I'm having trouble understanding this class and getting it to work properly, here is the piece of code where I use it:

MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:_videoURL];
UIImage *videoThumbnail = [moviePlayer thumbnailImageAtTime:0 timeOption:MPMovieTimeOptionNearestKeyFrame];
[lastImageView setImage:videoThumbnail];

[moviePlayer setControlStyle:MPMovieControlStyleNone];
[moviePlayer setShouldAutoplay:YES];
[moviePlayer prepareToPlay];

[moviePlayer.view setFrame:lastImageView.frame];
moviePlayer.view.transform = CGAffineTransformMakeRotation((90*M_PI)/180);
[self.view addSubview:moviePlayer.view];

[moviePlayer play];

The only reason why the videoThumbnail line is still there is because i didn't get the video to play until I was just trying it out to see if it would get the image from there and then it suddenly began to work... sort of. Now it plays for 2-3 secs and then terminates without sending MPMoviePlayerPlaybackDidFinishNotification or MPMoviePlayerPlaybackStateDidChangeNotification I googled around a bit and couldn't find any useful tips, could someone tell me what's wrong or what i am forgetting

回答1:

If you're not assigning the newly created MPMoviePlayerController instance to anything other than a variable with local scope (moviePlayer), then the movie player will be deallocated before the movie gets playing. (I imagine the thumbnailImageAtTime call keeps it around for a bit longer.)

Try assigning the movie player instance to a retained (strong) instance variable or property. Of course it should be released when finished, as multiple movie player instances don't play well together.

Also, note that, as of iOS 5, calling prepareToPlay is required. The following is from chapter 28 of Matt Neuberg's Programming iOS 5, Second Edition:

Before you can display a movie in your interface with an MPMoviePlayerController, you must call prepareToPlay, which is supplied through the MPMediaPlayer protocol (adopted by MPMoviePlayerController). This requirement is new in iOS 5, and is a major difference from previous versions of the system; your old code can break if it didn’t make this call.