Programmatically playing Video in IOS

by / Friday, 30 August 2013 / Published in Android

In IOS we can play video files programmatically as per our requirement.To do so we need to follow a few steps.First of all we need to add MediaPlayer framework to our project from linked frameworks.Then we need to drag the video file,which we want to play,in our project.Now in the .h file of our controller we need to add a MPMoviePlayerController type variable and an UIView.Synthesize these variables in the .m file.Now we are adding a UIButton from storyboard.On click of the button we will write the code to play the video.We are also adding a button to the right top of the view which will terminate the video instantly.Beside this the video will stop automatically when it is finished and the view will disappear.Here is the code to play video programmatically:

In .h file first import MediaPlayer.h.Then add

@property (nonatomic, retain) UIView* playerView;

@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;

Then in the .m file


playerView=[[UIView alloc] init];

UIButton *stopPlayerBtn = [UIButton buttonWithType:UIButtonTypeCustom];

[stopPlayerBtn addTarget:self



NSString *filepath   =   [[NSBundle mainBundle] pathForResource:@"help" ofType:@"mp4"];

NSURL    *fileURL    =   [NSURL fileURLWithPath:filepath];

moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];

[[NSNotificationCenter defaultCenter] addObserver:self




if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {

playerView.frame=CGRectMake(10, 90, self.view.frame.size.width-20, self.view.frame.size.height-100);

[moviePlayerController.view setFrame:CGRectMake(0,50,playerView.frame.size.width,playerView.frame.size.height-50)];

[stopPlayerBtn setImage:[UIImage imageNamed:@"close_btn_ipad.png"] forState:UIControlStateNormal];

[stopPlayerBtn setFrame:CGRectMake(playerView.frame.size.width-65, 10, 60,30)];



playerView.frame=CGRectMake(10, 50, self.view.frame.size.width-20, self.view.frame.size.height-60);

[moviePlayerController.view setFrame:CGRectMake(0,48,playerView.frame.size.width,playerView.frame.size.height-48)];

[stopPlayerBtn setImage:[UIImage imageNamed:@"close_btn1@2x.png"] forState:UIControlStateNormal];

[stopPlayerBtn setFrame:CGRectMake(playerView.frame.size.width-61, 10, 56,28)];


playerView.backgroundColor=[UIColor blackColor];


playerView.layer.borderColor=[UIColor whiteColor].CGColor;

[playerView addSubview:stopPlayerBtn];

[playerView addSubview:moviePlayerController.view];

[moviePlayerController play];

[self.view addSubview:playerView];

Then in the button action we need to add

[self playVideo];