Sunday, March 11, 2012

Video for iPhone/iPad using MPMoviePlayerController

First of all, we need to add the framework MediaPlayer to the project (MediaPlayer.framework) and then include the header file:
#import <MediaPlayer/MediaPlayer.h>
Suppose we saved the  MP4 file on disk. We have to provide the path in our code:
NSString *path = [[NSBundle mainBundle] pathForResource:@"nombre-video-sin-ext" ofType:@"mp4"];
NSURL *url = [NSURL fileURLWithPath:path];

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:url];
Now we have to set the video size and position. It is worth noting that MPMoviePlayerController inherits from UIViewController so we set the player.view properties.
player.view.frame = CGRectMake(50, 50, 698, 500);
[self.view addSubview:player.view];
[player prepareToPlay];
Finally, if we want to manage the video we will use:
[player play];
[player pause];
[player stop];
If we want to perform an action when the video ends, we can use notifications. For example:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(movieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
y pass the object player as a parameter to the function movieFinishedCallback:
- (void) movieFinishedCallback:(NSNotification*) aNotification {
MPMoviePlayerController *player = [aNotification object];
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
[player stop];
[player autorelease];
}
We are ready to watch videos on iPad or iPhone.