Wednesday 18 December 2013

How to play a video file in iPhone/iPad application

Step1:  Repeat step1 & step2 of " Introducation 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 mainBundle] pathForResource:@"Walk through_16.mov" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:urlStr];
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL: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...

No comments:

Post a Comment

Comment