Create a Simple App for Video Recording and Playback

http://www.appcoda.com/video-recording-playback-ios-programming/

In the previous post we covered how to create a simple camera app. In this post, we’re going to create a similar application but for video recording and playback.

The iOS API for recording and playing videos can be a little bit confusing for the newcomer, as there are several options available. If you just want to play a video, you can use the MediaPlayer framework, which allows us to play a video stored locally in our device, or from a remote location. However, if you need advanced features such as media asset management, media editing, track management, and others, you have to use the AVFoundation framework. This post will only cover the MediaPlayer framework.

On top of that, the MediaPlayer framework brings us two main classes to display videos or movies. If you want to display a video immediately and inline (e.g. a subview smaller than the full screen), you should use the MPMoviePlayerController. By using MPMoviePlayerController, playback occurs in a view owned by the movie player. You can incorporate a movie player’s view into a view owned by your app. On the contrary, if you want to play a full screen video, for example by presenting the video modally, you should use the MPMoviePlayerViewController class. The MPMoviePlayerViewController class is designed to present a simple view controller for displaying full-screen movies.

In this tutorial, we will explain the MPMoviePlayerController but similar concept applies to the MPMoviePlayerViewController class.

Simple Video App Tutorial

Simple Video App Tutorial

Creating Xcode Project

Open Xcode and create a new Project, choose the template Single View Application as show below:

New Xcode Project using Single View Template

New Xcode Project using Single View Template

In the next screen enter VideoApp as the product name and set com.appcoda in the company identifier field. Select the Use Authomatic Reference Counting option, but unselect the Use Storyboard since we’re not going to use storyboards for this project. Press next and create the project:

Setting Project Options

Setting Project Options

Designing User Interface

Select the AppViewController.xib file from Xcode’s Navigator to display the View Controller on the Editor Pane. Drag and drop an UIButton at the bottom of the screen centered (use the recommended position indicated by the blue guidelines), and change its title to “Take Video”. The resulting view should look something like:

Adding a Take Video Button

Adding a Take Video Button

Please note that we’re not going to add to the xib file an UIView to display the video, as we’ll do that later programmatically.

Next, we have to create an IBAction for our button. In order to do that, change the Editor to the Assistant mode meanwhile the AppViewController.xib file is selected. The AppViewController.h file should be opened. Control and drag from the UIButton to the AppViewController.h and create an IBAction. Set the name as takeVideo, the type as UIButton and choose the Event that fires the action as “Touch Up Inside”.

Simple Video App - Take Video Button

Associate the button with code

Adding Media Frameworks

As we said before, we need the MediaPlayer framework in order to play a video. This framework is not included by default in our application, and so, we have to add it manually. Select the project from the Navigator pane. That should open in the editor a screen where we could change the general properties of our application. In the editor pane select the “Build Phases” tab, and from that tab, open the “Link Binary With Libraries” section, as it is shown in the next figure:

Simple Video App - Build Phase

Link Binary with Libraries

Next click on the “+” button to open the list of available frameworks, and from that list, select the MediaPlayer and click add:

Adding Media Frameworks

Adding Media Frameworks

Repeat the same procedures to include another framework, the MobileCoreServices. We include this framework as we need to use some constants related to videos.

Writing the VideoApp Code

Open the AppViewController.h file and add the following code to include the necessary header files:

1
2
#import <MediaPlayer/MediaPlayer.h>
#import <MobileCoreServices/MobileCoreServices.h>

As we’re going to use an UIImagePickerController to record the video, our class has to implement the UIImagePickerControllerDelegate (refer to our previous Camera post for more information about this protocol). Additionally, we will implement the protocol UINavigationControllerDelegate as we’re going to present the picker modally.

1
@interface APPViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

And finally, add two properties. The movieURL property will contain the address of the current video to display, and the movieController property is the view where we will play the video.

1
2
@property (copy,   nonatomic) NSURL *movieURL;
@property (strong, nonatomic) MPMoviePlayerController *movieController;

If you did everything correctly, your AppViewController.h file should be something like:

1
2
3
4
5
6
7
8
9
10
11
12
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import <MobileCoreServices/MobileCoreServices.h>@interface APPViewController : UIViewController;
  UIImagePickerControllerDelegate, UINavigationControllerDelegate;@property (copy,      nonatomic) NSURL *movieURL;
@property (strong, nonatomic) MPMoviePlayerController *movieController;- (IBAction)takeVideo:(UIButton *)sender;

@end

Implementing Picker Controller for Video Recording

When the user taps the “Take Video” button, the takeVideo method is called. This method is responsible to create, configure and display the image picker. We’ll implement the method using the below code:

1
2
3
4
5
6
7
8
9
10
11

– (IBAction)takeVideo:(UIButton *)sender {

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];

[self presentViewController:picker animated:YES completion:NULL];

}

The implementation of delegate protocol shouldn’t be new to you. In the above code, we specify self as the delegate of the picker protocol. As we allow user to edit the recorded video, we set theallowsEditing property as YES. As explained in the previous tutorial, UIImagePickerController supports two types of sources: camera and photo library. Here we specify to use camera as the source type. Lastly, we specify the media type as kUTTypeMovie. When capturing media, the value of this property determines the camera interface to display. By default, it’s set for photo taking. As we want to let use to capture video, we use kUTTypeMovie.

When user finishes recording the video (that is, after tapping the “Use” button), thedidFinishPickingMediaWithInfo method is called with the info paraemeter containing the filesystem URL for the movie just picked. In this method, we save the URL of the video (please note that this video is not saved in the photo library unless we do it explicitly). Finally, we dismiss the picker.

1
2
3
4
5
6
7

– (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

self.movieURL = info[UIImagePickerControllerMediaURL];

[picker dismissViewControllerAnimated:YES completion:NULL];

}

The picker has another method that we should implement – the imagePickerControllerDidCancel. As its name suggests, it is invoked when user cancels the video recording. In this case, we simply dismiss the picker.

1
2
3
4
5

– (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

[picker dismissViewControllerAnimated:YES completion:NULL];

}

Implementing Video View for Video Playback

We are going to create and present our MPMoviePlayerController in the viewDidAppear method. It might seems a bit strange to use this method to present the movie player instead of using thedidFinishPickingMediaWithInfo method of the picker. But there is a good reason to do so. As we mentioned in the introduction, there are several incompatibilities among different video players. One of the incompatibilities is that there can only be one player per application and it turns out that the UIImagePickerController already comes with one player. So, we cannot create our MPMoviePlayerController until the picker is deallocated.

1
2
3
4
5
6
7
8
9
10
11

– (void)viewDidAppear:(BOOL)animated {

self.movieController = [[MPMoviePlayerController alloc] init];

[self.movieController setContentURL:self.movieURL];
[self.movieController.view setFrame:CGRectMake (0, 0, 320, 476)];
[self.view addSubview:self.movieController.view];

[self.movieController play];

}

The above code for creating and showing the video player is pretty straightforward. First we create the video player and assign the URL with the address of the video. Then we change the size of the view to leave some free space for the “Take Video” button. And finally, we present the view and play the video.

Using the Movie Player Notifications

A nice feature of the MPMoviePlayerController is that it has a collection of notifications that we can use to control the video playback. For example, when the video has finished playing, the MPMoviePlayerPlaybackDidFinishNotification will be sent. Add the following code to the viewDidAppear method, just before the [self.movieController play] statement:

1
2
3
4
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.movieController];

In the notification method we could do whatever we want. In our case we are going to do some some cleaning up: stop the video, remove its view, and free up the allocated memory (as said, there should be only one video player per application). Of course, don’t forget to remove the notification. Otherwise, it will be called twice!

1
2
3
4
5
6
7
8
9

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

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

[self.movieController stop];
[self.movieController.view removeFromSuperview];
self.movieController = nil;

}

Compile and Test the App

OK, it is time to compile and test our application. Like the Camera app we developed in the previous tutorial, you can’t test it using the built-in iPhone Simulator. You have to use a real device for the testing as the iPhone simulator doesn’t have a camera.

Simple Video App on iPhone

Editor’s note: If you’ve followed our development course from the very beginning, I think it’s time for you to register the iOS Developer Program and test your apps on a physical iPhone.

Download the Full Source Code

I hope you enjoy the tutorial and have a better idea about implementing video recording/playback in your app. For your complete reference, you can download the source code for the sample Xcode project here.

Advertisements