下面介紹蘋果重點推薦大家使用的框架類:AVPlayer和AVPlayerViewController
提供iOS四種源生視頻播放器框架比較(一)的連接:點擊跳轉(zhuǎn)
AVPlayer存在于AVFoundation中鸣剪,它更加接近于底層丈积,所以靈活性極高。主要用來實現(xiàn)自定義播放器功能江滨,沒有控制界面,顯示時需要借助AVPlayerLayer來進(jìn)行顯示唬滑,該播放器圖層繼承于CALayer告唆。
代碼實現(xiàn):
//導(dǎo)入頭文件
#import<AVFoundation/AVFoundation.h>
// 強(qiáng)引用
@property(nonatomic,strong)AVPlayer * player;
//懶加載
- (AVPlayer *)player
{
if (_player == nil) {
// 加載網(wǎng)絡(luò)資源
//? ? NSString *urlString = @"http://baobab.wdjcdn.com/14676170652191(23).mp4";
//? ? NSURL *url = [NSURL URLWithString:urlString];
//設(shè)置資源文件路徑 //可以播放網(wǎng)絡(luò)資源擒悬,
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"minion_01.mp4" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:filePath];
AVAsset *asset = [AVAsset assetWithURL:url];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
_player = [[AVPlayer alloc] initWithPlayerItem:item];
//注意點:此方法不能使用構(gòu)造方法,不然不會顯示稻艰,只會有聲音
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
[self.view.layer addSublayer:playerLayer];
playerLayer.frame = [UIScreen mainScreen].bounds;
self.layer = playerLayer;
}
return _player;
}
實現(xiàn)播放,暫停尊勿,結(jié)束功能
- (IBAction)pauseAction:(id)sender {
[self.player pause];
}
- (IBAction)playMovieAction:(id)sender {
[self.player play];
}
- (IBAction)endAction:(id)sender {
//注意此時self.player 一定要釋放,不然再次播放無法開啟
self.player = nil;
[self.layer removeFromSuperlayer];
//注意釋放內(nèi)存
self.layer = nil;
}
自定義播放器有許多非常好的框架元扔,可以滿足我們的開發(fā)需要,向大家推薦一篇使用AVPlayer自定義播放器的文章摇展,有開發(fā)需要的可以學(xué)習(xí)一下:鏈接
下面介紹一下AVPlayerViewController溺忧,蘋果在iOS8.0推出的集成度非常高,推薦大家使用盯孙,下面介紹一下它的優(yōu)點:自帶的播放控制UI, 不需要手動添加,此控制器是視圖控制器, 可以彈出, 可以壓棧也可以手動調(diào)整視圖大小, 添加到其他視圖上振惰。
實現(xiàn)代碼:
# 導(dǎo)入頭文件
#import<AVFoundation/AVFoundation.h>
#import<AVKit/AVKit.h>
//注意強(qiáng)引用
@property(nonatomic,strong)AVPlayerViewController * playerVC;
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"minion_01.mp4" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:filePath];
AVPlayer *player = [[AVPlayer alloc] initWithURL:url];
self.playerVC = [[AVPlayerViewController alloc] init];
self.playerVC.player = player;
// 設(shè)置縮放模式
self.playerVC.videoGravity = AVLayerVideoGravityResizeAspect;
// 是否顯示媒體播放組件
self.playerVC.showsPlaybackControls = YES;
//界面實現(xiàn)時開始播放
[self.playerVC.player play];
//播放方式有兩種,任選其中一種即可
//第一種方式:可以選擇在本控制器里播放骑晶,可以自定義播放器的位置和大小
//? ? self.playerVC.view.frame = CGRectMake(0, 150, self.view.frame.size.width, 300);
//? ? [self addChildViewController:self.playerVC];
//? ? [self.view addSubview:self.playerVC.view];
// 第二種方式:可以模態(tài)視頻控制器進(jìn)行播放
[self presentViewController:self.playerVC animated:YES completion:nil];
最后附上四種框架的全部測試demo:https://github.com/conghuasijidan/MoviePlayer.git