iOS视频播放器AVPlayer
需要导入系统的 AVFoundation
一、基本使用
(1).AVPlayerItem 播放对象
AVPlayerItem* item = [AVPlayerItem playerItemWithURL:_url];
根据url可以获取到播放对象
(2). AVPlayer 播放器对象
AVPlayer * player = [AVPlayerplayerWithPlayerItem:_playerItem];
根据item获取播放器
(3).AVPlayerLayer 播放器图层
AVPlayerLayer*playerLayer=[AVPlayerLayerplayerLayerWithPlayer:self.player];
根据播放器获取播放图层,AVPlayerLayer 是layer,需要将它添加到view的layer上面显示
[view.layer addSublayer:playerLayer]
///// 播放和暂停、播放速度//////
[player play];// 播放视频
[player pause]; // 暂停
player.rate=0.1; // 设置视频的播放速度
二、视频播放状态
(1)// 视频播放完的系统通知
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(playbackFinished:)name:AVPlayerItemDidPlayToEndTimeNotificationobject:self.player.currentItem];
(2)// 跳转到那个时间
[player seekToTime:CMTimeMake(0,1)];
(3)// 时间变化
AVPlayerItem*playerItem=self.player.currentItem;
//这里设置每秒执行一次
__weaktypeof(self) weakSelf=self;//设置self的弱应用放置block循环引用
[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0,10)queue:dispatch_get_main_queue()usingBlock:^(CMTimetime) {
// 当前时间
float current=CMTimeGetSeconds(time);
// 总得时间
float total=CMTimeGetSeconds([playerItemduration]);
//NSLog(@"当前已经播放%.2fs.",current);
}
}];
(4) // kvo 监听 视频开始状态 还有 缓冲进度
// 视频状态变化
[_playerItemaddObserver:selfforKeyPath:@"status"options:NSKeyValueObservingOptionNewcontext:nil];
// 视频缓冲
[_playerItemaddObserver:selfforKeyPath:@"loadedTimeRanges"options:NSKeyValueObservingOptionNewcontext:nil];
// 在这里 实现
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void*)context
{
if([keyPathisEqualToString:@"status"]) {
NSLog(@"%@",change);
NSIntegerne = [[changeobjectForKey:@"new"]integerValue];
if(ne ==AVPlayerStatusReadyToPlay) {
[_player play];
float total=CMTimeGetSeconds([_playerItemduration]);
}else{
}
}else{
float total=CMTimeGetSeconds([_playerItem duration]);
NSArray*array=_playerItem.loadedTimeRanges;
CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
float startSeconds =CMTimeGetSeconds(timeRange.start);
float durationSeconds =CMTimeGetSeconds(timeRange.duration);
NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
//NSLog(@"共缓冲:%.2f",totalBuffer);
//NSLog(@" %f ~~~~~~~%f",totalBuffer,total);
}
}
}
(5)最后 加上 iOS自定义系统音量