如何从iOS中的本地或服务器URL播放视频

Nik*_*hil 16 ios

如何从iOS中的Internet URL或本地文件播放.mp4或.mov视频?

Meh*_*tri 29

1.首先在XCode中添加MediaPlayer.Framework

2.然后在viewController的.h文件中添加#import <MediaPlayer/MediaPlayer.h>

3.现在在viewDidLoad方法中实现此代码

     //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];  
Run Code Online (Sandbox Code Playgroud)

对于Orientation请添加此代码

 - (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;
 }
Run Code Online (Sandbox Code Playgroud)

在这段代码中,moviePlayerController是在.h文件中声明的MPMoviePlayerController


Bou*_*rne 9

这是一个老问题,但仍然相关,iOS 9已弃用MPMoviePlayerController.AVMoviePlayer使用的新东西,示例代码:

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];
Run Code Online (Sandbox Code Playgroud)