Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a video from either a local or a server URL in iOS

Tags:

ios

How can I play a .mp4 or .mov video from either an Internet URL or a local file in iOS?

like image 381
Nikhil Avatar asked May 17 '11 06:05

Nikhil


People also ask

How do I add a video to my Xcode project?

From the toolbar, select Add Media. From the Insert New menu, select Video. Select the main Record button of the project. Your video will start recording alongside your project recording.


2 Answers

1.First of all add MediaPlayer.Framework in XCode

2.Then add #import < MediaPlayer/MediaPlayer.h > in your viewController's .h file

3.Now implement this code in your viewDidLoad Method

     //NSString *filepath = [[NSBundle mainBundle] pathForResource:@"aaa" ofType:@"mp4"];  
     //NSURL    *fileURL = [NSURL fileURLWithPath:filepath];  

     NSURL *fileURL = [NSURL URLWithString:@"http://www.ebookfrenzy.com/ios_book/movie/movie.mov"];

     moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL]; 
     [moviePlayerController.view setFrame:CGRectMake(0, 70, 320, 270)]; 
     [self.view addSubview:moviePlayerController.view];  
     moviePlayerController.fullscreen = YES;  
     [moviePlayerController play];  

For Orientation Please add this code

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
     // Return YES for supported orientations
          if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
         [moviePlayerController.view setFrame:CGRectMake(0, 70, 320, 270)]; 
     } else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
         [moviePlayerController.view setFrame:CGRectMake(0, 0, 480, 320)]; 
     }
     return YES;
 }

In this code moviePlayerController is MPMoviePlayerController declared in .h file

like image 90
Mehul Mistri Avatar answered Sep 17 '22 17:09

Mehul Mistri


This is an old question but still relevant and iOS 9 has deprecated MPMoviePlayerController. The new thing to use if AVMoviePlayer, example code:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"vid" ofType:@"mp4"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
self.avPlayer = [AVPlayer playerWithURL:fileURL];

AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
layer.frame = self.view.bounds;
[self.view.layer addSublayer: layer];

[self.avPlayer play];
like image 28
Bourne Avatar answered Sep 17 '22 17:09

Bourne