Thursday 8 March 2012

Tutorial #2: Playing a Video in a iOS App

Step 1: Import the MediaPlayer.framework

In your project, select the main project file and then the "Build Phases" tab. Expand the "Link Binary with Libraries" section and hit the "+". Select the MediaPlayer.framework and click "Add".

Step 2: Create an instance variable in your view controller to hold your media player.

Make an import statement at the top of your view controller for the media player framework.


#import "MediaPlayer/MediaPlayer.h"

Next, using the storyboard and split-screen view (see previous tutorial) add an IBAction for a button in your view that you would like to play a video. Give it a descriptive name.

Lastly, create a variable to hold your media player.

@property (strong, nonatomic) MPMoviePlayerViewController *player;

Step 3: Implement your video player method

Your video player method should look like this.

- (IBAction)playVideo:(id)sender {
    
    NSString *videoPath = [[NSBundle mainBundle] pathForResource:@"yourVideo" 
       ofType:@"m4v"];
    
    player = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL
       fileURLWithPath:videoPath]];
    
    [self presentMoviePlayerViewControllerAnimated:player]; 
}

The above code will grab a path for your video file (in this case, yourVideo.m4v). Then, it will instantiate a new MPMoviePlayerViewController object called "player" with the video file. It then presents that view controller to the user.

That's it. Simple :)

A couple tips. If you're using this code and find that it's not working for you, it is possible that your path isn't being set right. Sometimes, you need to manually identify what resources you would like build into your app bundle. If you're getting a mystery SIGABRT when you try to play your video, this could be why. To make sure your video is being bundled, select your main project file and click on "Build Phases". Expand the "Copy Bundle Resources" item and check to see if your video is listed. If it isn't, just use the "+" at the bottom to add it in.

Happy coding!

No comments:

Post a Comment