Tag Archive for 'movie'

How to play a video within your iphone app

Sometimes you need to show a short sequence of a video file within your app to enrich your content. However, this is a very simple task. Everything you need is a H.264 or MPEG-4 video included in your project and you also have to reference the MediaPlayer framework. After that simply use the following code to start your video:

...
//specify the URL of the movie
NSURL *movieUrl = [NSURL fileURLWithPath:
            [[NSBundle mainBundle] pathForResource:@"mymovie" 
            ofType:@"m4v"]];
 
//create a new instance of MPMoviePlayerController
MPMoviePlayerController* myMovie=[[MPMoviePlayerController alloc] 
            initWithContentURL:movieUrl];
 
//disable scaling of our movie
myMovie.scalingMode = MPMovieScalingModeNone;
 
//don't show any controls
myMovie.movieControlMode = MPMovieControlModeHidden;
 
//you can specify at which time the movie should 
//start playing (default is 0.0)
myMovie.initialPlaybackTime = 2.0;
 
//register a callback method which will be called
//after the movie finished
[[NSNotificationCenter defaultCenter] addObserver:self 
            selector:@selector(movieFinished:) 
            name:MPMoviePlayerPlaybackDidFinishNotification 
            object:myMovie]; 
 
//start the movie (asynchronous method)
[myMovie play];
...

A callback method is used to release your media player instance, which you can simply add to your current class:

-(void)movieFinished:(NSNotification*)aNotification 
{
	//get the movie instance from the notification object
	MPMoviePlayerController* myMovie=[aNotification object]; 
	[[NSNotificationCenter defaultCenter] removeObserver:self 
                    name:MPMoviePlayerPlaybackDidFinishNotification 
                    object:myMovie]; 
 
	//release the movie
	[myMovie release]; 
}

And that’s all folks. The code shown above works with iPhone OS 2.0 or greater. In the next release of the iPhone OS there maybe will be some more enhancements on playing movies within your app.

Cheers,

Andreas