Video Playback from within an iOS 5 iPhone Application

Follow Techotopia on Twitter Bookmark and Share

From Techotopia

Jump to: navigation, search
PreviousTable of ContentsNext
An Example iOS 5 iPhone Camera ApplicationPlaying Audio on an iPhone using AVAudioPlayer


Purchase the fully updated iOS 7 edition of this book in eBook ($12.99) or Print ($32.99) format

iOS 7 App Development Essentails Print and eBook (ePub/PDF/Kindle) editions contain 89 chapters.

Buy Print
Buy eBook


Whilst the iPhone 3GS model introduced support for recording videos using the built in camera, all iPhone models and iOS versions have included support for video playback. Video playback support in iOS 5 is provided by the 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 5 iPhone application.

Contents



[edit] 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.

[edit] 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.

[edit] The iPhone Movie Player Example Application

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

Begin by launching Xcode and creating a new iOS iPhone application project based on the Single View-based application template, naming the product and class prefix movie when prompted to do so.

[edit] 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.

[edit] Declaring the Action Method and MoviePlayer Instance

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 and also add a reference to an instance of the MPMoviePlayerController class:

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

@interface movieViewController : UIViewController
{
    MPMoviePlayerController *moviePlayer;
}
@property (strong, nonatomic) MPMoviePlayerController *moviePlayer;
-(IBAction) playMovie;
@end

Select the movieViewController.m and add the @synthesize directive for the moviePlayer:

#import "movieViewController.h"

@implementation movieViewController
@synthesize moviePlayer;
.
.
@end

[edit] 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 -> Show 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.

[edit] 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 movie from a remote network location. Begin by finding a suitable movie file for inclusion in the application. Any movie recorded by an iPhone 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.

[edit] Implementing the Action Method

The next step is to write the code for the action method so that video playback is initiated 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"]];
    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.

[edit] 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 and the @synthesize directive as follows:

- (void) moviePlayBackDidFinish:(NSNotification*)notification {
    MPMoviePlayerController *player = [notification object];
    [[NSNotificationCenter defaultCenter] 
      removeObserver:self
      name:MPMoviePlayerPlaybackDidFinishNotification
      object:player];

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

[edit] 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 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 from within an iPhone iOS 5 application

Figure 51-1

[edit] 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"];
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];

The video file may also be selected from the device camera roll or photo library as outlined in An Example iOS 5 iPhone Camera Application.


Purchase the fully updated iOS 7 edition of this book in eBook ($12.99) or Print ($32.99) format

iOS 7 App Development Essentails Print and eBook (ePub/PDF/Kindle) editions contain 89 chapters.

Buy Print
Buy eBook



PreviousTable of ContentsNext
An Example iOS 5 iPhone Camera ApplicationPlaying Audio on an iPhone using AVAudioPlayer
Views
Personal tools

Find us on Facebook