// 声明两个对象
@property (nonatomic,strong)AVPlayer *player;//播放器对象
@property (nonatomic,strong)AVPlayerItem *currentPlayerItem;
// 初始化播放器
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:FullImageUrl(self.messageViewCover.userModel.video_url)];
self.currentPlayerItem = playerItem;
self.player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
AVPlayerLayer *avLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
avLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
avLayer.frame = self.videoImage.bounds;
[self.videoImage.layer addSublayer:avLayer];
// 播放完成通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(runLoopTheMovie:) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
//1.注册观察者,监测播放器属性
//观察Status属性,可以在加载成功之后得到视频的长度
[self.player.currentItem addObserver:self forKeyPath:@“status” options:NSKeyValueObservingOptionNew context:nil];
//观察loadedTimeRanges,可以获取缓存进度,实现缓冲进度条
[self.player.currentItem addObserver:self forKeyPath:@“loadedTimeRanges” options:NSKeyValueObservingOptionNew context:nil];
// 播放
[self.player play];
//循环播放用到这个方法
- (void)runLoopTheMovie:(NSNotification *)notification{
AVPlayerItem *playerItem = notification.object;
[playerItem seekToTime:kCMTimeZero];
[_player play];
}
//2.添加属性观察
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
AVPlayerItem *playerItem = (AVPlayerItem *)object;
if ([keyPath isEqualToString:@“status”]) {
//获取playerItem的status属性最新的状态
AVPlayerStatus status = [[change objectForKey:@“new”] intValue];
switch (status) {
case AVPlayerStatusReadyToPlay:{
//获取视频长度
CMTime duration = playerItem.duration;
//开始播放视频
// [self.player play];
break;
}
case AVPlayerStatusFailed:{//视频加载失败,点击重新加载
break;
}
case AVPlayerStatusUnknown:{
NSLog(@“未知问题:AVPlayerStatusUnknown”);
break;
}
default:
break;
}
} else if ([keyPath isEqualToString:@“loadedTimeRanges”]) {
// //获取视频缓冲进度数组,这些缓冲的数组可能不是连续的
// NSArray *loadedTimeRanges = playerItem.loadedTimeRanges;
// //获取最新的缓冲区间
// CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
// //缓冲区间的开始的时间
// NSTimeInterval loadStartSeconds = CMTimeGetSeconds(timeRange.start);
// //缓冲区间的时长
// NSTimeInterval loadDurationSeconds = CMTimeGetSeconds(timeRange.duration);
// //视频缓冲时间总长度
// NSTimeInterval currentLoadTotalTime = loadStartSeconds + loadDurationSeconds;
// //NSLog(@“开始缓冲:%f,缓冲时长:%f,总时间:%f”, loadStartSeconds, loadDurationSeconds, currentLoadTotalTime);
// //缓冲总时长
// _currentLoadTimeLabel.text = [self formatTimeWithTimeInterVal:currentLoadTotalTime];
// //视频的总时长
// _totalNeedLoadTimeLabel.text = [self formatTimeWithTimeInterVal:CMTimeGetSeconds(self.player.currentItem.duration)];
// //缓冲进度条的值
// _progressView.progress = currentLoadTotalTime/CMTimeGetSeconds(self.player.currentItem.duration);
}
}