和音频播放一样,ios也提供个很多的API。如mediaPlayer.framework下的MPMediaPlayerController、AVFounditon.framework下的AVPlayer和AVKit下的AVPlayerViewcontroller。下面先看一下下图
有上面的三幅图可以看出,MPMovieplayerController已经在ios9.0中被废弃了,用来替代的是AVPlayerViewcontroller。尽管如此,但还是说一下比较熟悉的MPMovieplayerController.
1、MPMovieplayerController
<1>初始化MPMovieplayerController
// 创建本地URL(也可创建基于网络的URL)
NSURL* movieUrl = [[NSBundle mainBundle]URLForResource:@"movie" withExtension:@"mp4"];
// 使用指定URL创建MPMoviePlayerController
// MPMoviePlayerController将会播放该URL对应的视频
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieUrl];
/ 设置该播放器的控制条风格。
moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
// 设置该播放器的缩放模式
moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
[moviePlayer.view setFrame: CGRectMake(0 , 0 , 380 , 320)];
[self.movieView addSubview: moviePlayer.view];
[moviePlayer play];
[moviePlayer pause];
[moviePlayer stop];
由于属性太多,这里只列出能完成简单的播放器的属性,其他属性可在头文件中查找。
AVPlayer既可以播放音乐又可以播放视频;使用AVPlayer不能直接显示视频,必须要加入AVPlayerLayer中,并添加到其他能显示的layer中。
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"backspace" ofType:@"mov"];
NSURL *sourceMovieURL = [NSURL fileURLWithPath:filePath];
AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
playerLayer.frame = self.view.layer.bounds;
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.view.layer addSublayer:playerLayer];
[player play];
3、AVPlayerViewcontroller
AVPlayerViewcontroller继承自UIViewController,一般适用于点击一个视频缩略图,modal出一个新的界面来进行播放的情况。
用法:
AVPlayerViewController *player = [[AVPlayerViewController alloc]init];
player.player = [[AVPlayer alloc]initWithURL:movieUrl];
[self presentViewController:player animated:YES completion:nil];