Crossed Ads

Tuesday 2 May 2017

How to create Video Player in iOS using Objective-C ?

VIDEO PLAYER in Objective-C


Video can be played in iOS app using class AVPlayerController that provides playback of video data from a file or memory.

Follow the below steps to build an Video playing App:

Step 1: Create a Single View Application 


Next, enter product name as VideoPlayerDemo and select language as Objective-C.



Step 2: Firstly, add any video file into the project by simply drag and drop method (make sure below selected option in 2nd image should be checked for keeping copy of that file into our project).  



Step 3: Now, just go to main.storyboard and set a button named Play Video on controller. 



Step 4: Go to ViewController.h file and import AVFoundation & AVKit Framework. Also set property of Action connection for the Play Video button.
Code will look like:- 



Step 5: In ViewController.m file, type the below code in the curly braces of button method. 



Here is the explanation of above code as under:

In below line of code, we are storing path of video file in variable of type string named path. One can access file’s path using NSBundle class and then its class method name mainBundle, then instance method named pathForResource where you need to specify only filename (Case Sensitive) and ofType where you need to specify its extension (without dot sign).

NSString *path = [NSBundle mainBundle] pathForResource: @“Video” ofType: @“mp4”];

Thereafter, path of video file will be passed to url variable of type URL using the class method fileURLWithPath as mentioned below:

NSURL *url = [NSURL fileURLWithPath: path];

Now, creating an instance of AVPlayer where url is passed using class method playerWithURL as shown below.

AVPlayer *player = [AVPlayer playerWithURL: url];

Furthermore, we need to create instance of AVPlayerController which is used to play video and give allocation with initialisation.

AVPlayerController *controller = [[AVPlayerController alloc] init];

We need to pass player instance to the player of controller to play a video by using below code.

controller.player = player;

To run the video on full screen, we need to assign present view’ bounds to controller’s view frame as shown below.

controller.view.frame = self.view.bounds;

This already created controller’s view (subview) is not added to the view of present controller so for that below code is used to add the same.

[ [self view] addSubView: controller.view];

Simply play the player now.

[player play];


Step 6: Run the App, you will see video like below.  





Enjoy Music with Video 😇


Visit below link for the video of the same:


No comments:

Post a Comment