Video Playback from within an iOS 4 iPhone Application

From Techotopia
Revision as of 20:15, 27 October 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0"> " to "<table border="0" cellspacing="0" width="100%">")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
PreviousTable of ContentsNext
An Example iOS 4 iPhone Camera ApplicationBasic iOS 4 iPhone Animation using Core Animation


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


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 4 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 4 iPhone 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

<google>ADSDAQBOX_FLOW</google> 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 iPhone Movie Player Example Application

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

Begin by launching Xcode and creating a new iOS iPhone application project based on 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. To add this framework to the movie project, ctrl-click on the Frameworks entry in the Groups & Files panel of the main Xcode window and select Add -> Existing Frameworks… from the menu. From the resulting list of available frameworks, select MediaPlayer.framework and click on Add.

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

Once the changes have been made, save the file before proceeding.

Designing the User Interface

Double click on the movieViewController.xib file to load it into Interface Builder. 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 (Command+2), click on the circle to the right of the Touch Up Inside event and drag the blue line to the File’s Owner entry in the documents window. From the resulting menu, select the playMove action method.

Save the design and exit from Interface Builder.

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 will suffice for this purpose.

Copy the movie file to the system on which Xcode is running and name it movie.mov. In the main Xcode project window, ctrl-click on the Resources entry in the Groups & Files panel and select Add -> New File…. Browse to the location of the movie.mov file and add it to the project, accepting the default settings on the import settings 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];
}

Enabling Device Rotation

Most users prefer to watch video with their iPhone held in landscape orientation. To enable the video to be watched in landscape mode it is necessary to uncomment and modify the shouldAutorotateToInterfaceOrientation method located in the movieViewController.m file:

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    //return (interfaceOrientation == UIInterfaceOrientationPortrait);
        return YES;
}

Build and Run the Application

<google>IOSBOX</google> With the design and coding phases complete, all that remains is to build and run the application. Click on the Build and 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:


A video playing inside an iOS 4 iPhone 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 device camera roll or photo library as outlined in An Example iOS 4 iPhone Camera Application.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
An Example iOS 4 iPhone Camera ApplicationBasic iOS 4 iPhone Animation using Core Animation