1 Mar 2014

iPhone Development: Play video in iPhone sdk

Having a requirement of playing video in your app and the video is  stored locally in your app bundle.
Don't get panic as APPLE Inc. provided a media player framework that will allow you to play video files in your app.
MediaPlayer framework includes MPMoviePlayerController that will play video files for you. In this post i am going to tell you how you can use MPMoviePlayerController to play your video files.
First add MediaPlayer.framework to your project and also add video file to your project.
Now in your viewController file your the file in which you want to add video playing functionality
import MediaPlayer/MediaPlayer.h as given below

#import "MediaPlayer/MediaPlayer.h"

Now in your viewDidLoad get your path of video file as given below
 NSString *url = [[NSBundle mainBundle]
Create instance of MPMoviePlayerController and initialise it with the above url string by using method initWithContentURL 
 MPMoviePlayerController   *player =
    [[MPMoviePlayerController alloc]
     initWithContentURL:[NSURL fileURLWithPath:url]];
Then add notification observer so that your app will be notified when movie playback was finished.
    [[NSNotificationCenter defaultCenter]

In case of iPad you can give frame to your player 
        player.view.frame = CGRectMake(0, 70, 1024, 640);
Lastly, add your player to your own view
        [self.view addSubview:player.view];
And then you can start playing video file  using the method play
    //---play movie---
    [player play];

When your movie player stop playing video file, MPMOviePlayerPlaybackDidFinishNotification will be called 
- (void) movieFinishedCallback:(NSNotification*) aNotification {    MPMoviePlayerController *player = [aNotification object];    [[NSNotificationCenter defaultCenter]        removeObserver:self                  name:MPMoviePlayerPlaybackDidFinishNotification                object:player];        [player autorelease];     }

No comments:

Post a Comment