Tuesday, March 1, 2011

How to play a video file in iPhone/iPad app.


In this application You can play a video file for iPhone/iPad.


It will look like this:












Step1:  Repeat step1 & step2 of "Introduction to Xcode -How to Switch Views through Button" to create new project and name it as "playVideo"
 We will get 4 files in class folder named as:
"playVideoAppDelegate.h"
 "playVideoAppDelegate.m"




"playVideoViewController.h"
"playVideoViewController.m"
and "playVideoViewController.xib" file in Resource folder.

Step2: Add MediaPlayer.Framwork in Framwork folder.

Right click on Framwork folder -> Add -> Existing Framworks -> select MediaPlayer.Framwork -> click on Add button.

Step3: Add video file in Resource folder.
Right click on Resource folder -> Add -> Existing Files -> Browse for video file -> click on Add button.


Step4: Now let's type out the code:
Open playVideoViewController.h and make these changes:

#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>



@interface playVideoViewController : UIViewController {
MPMoviePlayerController *moviePlayer;
}

@end

Explanation of code:

#import <MediaPlayer/MediaPlayer.h>
Here, we are importing MediaPlayer.h file of MediaPlayer.Framwork to access controls for media file.

MPMoviePlayerController *moviePlayer;
Creating an object of MPMoviePlayerController class.



Step5: Open playVideoViewController.m and make these changes:

 -void)viewWillAppear:(BOOL)animated
{
NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"Walk through_16.mov" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:urlStr];
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
        [moviePlayer play];
}
Explanation of code:
-(void)viewWillAppear:(BOOL)animated
 {


This is a method which tells that what type of view will appear when it will load.

NSString *urlStr = [[NSBundle mainBundlepathForResource:@"Walk through_16.mov" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:urlStr];
moviePlayer = [[MPMoviePlayerController allocinitWithContentURL:url];
[moviePlayer play];

Extracting the path for resource(i.e.file to be play) and save it in urlStr. Converting its path into an URL and save it in url. Pass this url to moviePlayer. And at last it will play this.


Step6: Now its time to view your file in iPhone...




Just run this app...and enjoy your video.... :)

CLICK HERE to download source code.

Happy Coding :) 

3 comments: