Difference between revisions of "Video Playback from within an iOS 4 iPad Application (Xcode 4)"

From Techotopia
Jump to: navigation, search
(New page: Whilst the iPhone has always supported video playback, the appeal of watching on the smaller screen has always been less than ideal, especially for prolonged viewing periods. With its larg...)
(No difference)

Revision as of 19:59, 28 April 2011

Whilst the iPhone has always supported video playback, the appeal of watching on the smaller screen has always been less than ideal, especially for prolonged viewing periods. With its larger screen, the iPad is without question an excellent platform for video playback. Video playback support on the iPad, as with the iPhone, is provided by the iOS 4 MPMoviePlayerController class. This chapter presents an overview of the MPMoviePlayerController class followed step by step example of the use of this class to play a movie within an iOS 4 iPad application.


Contents


An Overview of the MPMoviePlayerController Class

The sole purpose of the MPMoviePlayerController is to play video content. It is initialized with the URL of the media to be played (either a path to a local movie file on the device or the URL of network based media). The movie player view is added as a subview of the current view, configured using a variety of properties and then displayed to the user. The playback window can run in a full screen mode, or embedded in an existing view.

By default, the movie player includes a number of controls that enable the user to manage the playback experience. The exact controls displayed to the user may be configured by setting the movie player’s controlStyle property. Playback may also be controlled from the application code by implementing the methods defined in the MPMediaPlayback protocol.

The MPMoviePlayerController class also employs the target-action model for notifying the application of events such as the movie starting, finishing, being paused, entering and leaving full screen mode etc.

Supported Video Formats

The MPMoviePlayerController class supports the playback of movies of type .mov, .mp4, .mpv and .3gp. In terms of compression, the class supports H.264 Baseline Profile Level 3.0 and MPEG-4 Part 2 video.


The iPad Movie Player Example Application

The objective of the remainder of this chapter to create a simple iPad application that will play back a video file when a button is pressed.

Begin by launching Xcode and creating a new iOS iPad application project using the View-based application template, naming the project movie when prompted to do so.

Adding the MediaPlayer Framework to the Project

The MPMoviePlayerController class is contained within the MediaPlayer framework. This framework must, therefore, be included in any projects that make use of this class. This can be achieved by selecting the product target entry from the project navigator panel (the top item named movie) and clicking on the Build Phases tab in the main panel. In the Link Binary with Libraries section click on the ‘+’ button, select the MediaPlayer.framework entry from the resulting panel and click on the Add button.

Declaring the Action Method

The application user interface is going to consist of a single button which, when pressed, will initiate the movie playback process. We therefore need to declare an action method called playMovie in our movieViewController.h file. It is also imperative that the <MediaPlayer/MediaPlayer.h> file be imported to avoid a catalog of unresolved references when the application is compiled:

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

@interface movieViewController : UIViewController {
}
-(IBAction) playMovie;
@end

Designing the User Interface

Select the movieViewController.xib file and display the Object library (View -> Utilities -> Object Library). Drag a single UIButton instance to the view window and change the text on the button to “Play Movie”. With the button selected display the connections inspector window (View -> Utilities -> Connections Inspector), click on the circle to the right of the Touch Up Inside event and drag the blue line to the File’s Owner object. From the resulting menu, select the playMove action method.

Adding the Video File to the Project Resources

Initially, the video file to be displayed to the user is going to be bundled on the device with the application. In a later section we will look at streaming a move from a remote network location. Begin by finding a suitable movie file for inclusion in the application. Any movie recorded by an iPhone or iPad 2 will suffice for this purpose.

Copy the movie file to the system on which Xcode is running and name it movie.mov. Locate the file in a Finder window and drag and drop it onto the Supporting Files folder in the project navigator panel.

Implementing the Action Method

The next step is to write the code for the action method so that the video is played to the user when the button is touched by the user. The code for the method should be placed in the movieViewController.m file as follows:

-(void)playMovie
{
     NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
                 pathForResource:@"MOVIE" ofType:@"MOV"]];
        MPMoviePlayerController *moviePlayer = 
            [[MPMoviePlayerController alloc] 
            initWithContentURL:url];

        [[NSNotificationCenter defaultCenter] addObserver:self
          selector:@selector(moviePlayBackDidFinish:)
          name:MPMoviePlayerPlaybackDidFinishNotification
          object:moviePlayer];

    moviePlayer.controlStyle = MPMovieControlStyleDefault;
    moviePlayer.shouldAutoplay = YES;
    [self.view addSubview:moviePlayer.view];
    [moviePlayer setFullscreen:YES animated:YES];
}

The above method constructs an NSURL object based on the video file that was added to the project resources. This is then used in the creation of a new instance of the MPMoviePlayerController class. A notification is then configured such that the moviePlaybackDidFinish method is called when the playback finishes. Next, properties are set to ensure that the standard movie controls are available to the user and that the movie automatically starts playing once it is ready. Finally the movie player object is added as a subview to the current view and displayed to the user in full screen mode.

The Target-Action Notification Method

The playButton action method declared that when the movie has finished playing the movie player object is to call a method named moviePlaybackDidFinish. It is the responsibility of this method to cancel the notification, remove the movie player interface from display and release the memory allocated to it. Edit the movieViewController.m file and add this method as follows:

- (void) moviePlayBackDidFinish:(NSNotification*)notification {

    MPMoviePlayerController *moviePlayer = [notification object];

    [[NSNotificationCenter defaultCenter] removeObserver:self      
              name:MPMoviePlayerPlaybackDidFinishNotification
              object:moviePlayer];

     if ([moviePlayer 
          respondsToSelector:@selector(setFullscreen:animated:)])
     {
              [moviePlayer.view removeFromSuperview];
     }
     [moviePlayer release];
}

Build and Run the Application

With the design and coding phases complete, all that remains is to build and run the application. Click on the Run button located in the toolbar of the main Xcode project window. Assuming that no errors occur, the application should launch within the iOS Simulator or device. Note that in addition to the application code, the movie.mov file added as a resource to the project also needs to be loaded. If a large video file was used it may take some time for before the application starts up. Once loaded, touching the Play Movie button should launch the movie player in full screen mode and playback should automatically begin:


Video playback in an iPad application


Accessing a Network based Video File

In the example created in this chapter the movie file was loaded alongside the application onto the device as a local resource file. The application may be modified to stream a movie file from a network based location by specifying the URL when creating an instance of the MPMoviePlayerController class. Continuing with the example application, the creation of the URL for the local file could be modified to specify an HTTP URL as follows:

NSURL *url = [NSURL URLWithString:@"http://www.ebookfrenzy.com/ios_book/movie/movie.mov"];
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];

The video file can also be selected from the iPad camera roll or photo library as outlined in An Example iOS 4 iPad Camera Application.