iOS 视频播放(AVPlayer)的使用
2019-06-14 本文已影响0人
Double丶K
小记:很久没有用系统播放器,都快忘没了.整理下,好记住
要实现系统视频播放的功能,就是使用下面的3个类,缺一不可.
AVPlayerItem:继承NSObject,可以理解为一个模型,里面有很多视频的信息,时间,播放状态,设置播放的连接,等等功能.
AVPlayer:播放器对象.播放,暂停,设置PlayerItem,时间监听的回调(addPeriodicTimeObserverForInterval),设置快进拖拽等方法(seekToTime)
AVPlayerLayer:播放器的占位layer
一:基本的播放功能
使用这三个类能实现最基本的播放功能,添加进度条,播放暂停按钮,调节声音大小,都需要自己去添加.
#import <AVFoundation/AVFoundation.h>
@property (nonatomic, strong) AVPlayerItem *playItem;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) AVPlayer *player;
//
_playItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:urlStr]];
self.player = [[AVPlayer alloc] initWithPlayerItem:_playItem];
_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
_playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 211);
//视频在AvPlayerLayer中的显示方式
_playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.view.layer addSublayer:_playerLayer];
//再调用播放,最好通过监听播放器的status为AVPlayerStatusReadyToPlay再开始播放
[_player play];
二:细节处理
这里只做了一个播放状态的监听
//播放完成的通知,用于循环播放等功能
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playDidFinish) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
//监听播放状态
[self.playItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//不用的时候移除监听
[self.playItem removeObserver:self forKeyPath:@"status"];
#pragma mark -------播放属性监听--------
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"status"]) {
switch (self.playItem.status) {
case AVPlayerStatusUnknown:
NSLog(@"KVO:未知状态,此时不能播放");
break;
case AVPlayerStatusReadyToPlay:
if (!_player.timeControlStatus || _player.timeControlStatus != AVPlayerTimeControlStatusPaused) {
[_player play];
}
NSLog(@"KVO:准备完毕,可以播放");
break;
case AVPlayerStatusFailed:
NSLog(@"KVO:加载失败,网络或者服务器出现问题");
break;
default:
break;
}
}
}