获取资源地址
NSURL *sourceMovieURL = [NSURL URLWithString:_videoUrl];
创建AVPlayerItem
self.playerItem = [AVPlayerItem playerItemWithURL:sourceMovieURL];
根据AVPlayerItem创建媒体播放器
self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
//如果切换地址 使用[self.player replaceCurrentItemWithPlayerItem:strongSelf.playerItem];
创建AVPlayerLayer,用于呈现视频
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
设置显示大小和位置
self.playerLayer.frame = self.superView.bounds;
设置拉伸模式
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
将播放器添加到当前view上,zPosition 默认值是0,值越高view的层级就越高,值越低就越低,因此我设置为-1,就在最下层。不会盖住其他的view。
self.playerLayer.zPosition = -1;
[self.layer addSublayer:self.playerLayer];
监测播放进度
[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
//已播放长度s
float current=CMTimeGetSeconds(time);
//视频总长度
float total=CMTimeGetSeconds([strongSelf.playerItem duration]);
}];
AVPlayerItem 监听事件
// 播放器状态(准备播放与播放错误)
[self.playerItem addObserver:self forKeyPath:@”status” options:NSKeyValueObservingOptionNew context:nil];
//监听播放器下载进度
[self.playerItem addObserver:self forKeyPath:@”loadedTimeRanges” options:NSKeyValueObservingOptionNew context:nil];
// 缓存数据不足
[self.playerItem addObserver:self forKeyPath:@”playbackBufferEmpty” options:NSKeyValueObservingOptionNew context:nil];
//缓存达到可播放进度
[self.playerItem addObserver:self forKeyPath:@”playbackLikelyToKeepUp” options:NSKeyValueObservingOptionNew context:nil];
监听播放状态与监听播放进度说明
//播放状态
if ([keyPath isEqualToString:@”status”]) {
if ([playerItem status] == AVPlayerStatusReadyToPlay) {
NSLog(@”开始播放”);
} else if ([playerItem status] == AVPlayerStatusFailed || [playerItem status] == AVPlayerStatusUnknown) {
NSLog(@”播放错误”);
}
}
//播放下载进度
if ([keyPath isEqualToString:@”loadedTimeRanges”]) { //监听播放器的下载进度
// 计算缓冲进度
NSArray *loadedTimeRanges = [playerItem loadedTimeRanges];
CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
NSTimeInterval timeInterval = startSeconds + durationSeconds;// 计算缓冲总进度
CMTime duration = playerItem.duration;
CGFloat totalDuration = CMTimeGetSeconds(duration);
[self.progressView setProgress:timeInterval / totalDuration animated:NO];
}
githubDemo地址:
播放器 断点续传 视频压缩 视频录制工程中的ZFVideoPalyer.h文件