參考
1.iOS通過AVPlayer打造自己的視頻播放器
2.基于 AVPlayer 自定義播放器
3.AVPlayer的基本使用
if (_player) {
return;
}
_playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:imageModel.videoPath]];
_player = [AVPlayer playerWithPlayerItem:_playerItem];
_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
_playerLayer.frame = gesture.view.bounds;
[gesture.view.layer addSublayer:_playerLayer];
[_player play];
//監聽當視頻播放結束時
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:[self.player currentItem]];
// //監聽播放失敗時
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playbackFailed:) name:AVPlayerItemFailedToPlayToEndTimeNotification object:[self.player currentItem]];
- (void)playbackFinished:(NSNotification *)notification {
AVPlayerItem *item = [notification object];
[item seekToTime:kCMTimeZero]; // item 跳轉到初始
if (item == _playerItem) {
[self resetPlayer];
}
}
- (void)resetPlayer {
if (_playerLayer) {
[_player pause];
[_playerLayer removeFromSuperlayer];
[_player replaceCurrentItemWithPlayerItem:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self];
_playerLayer = nil;
_playerItem = nil;
_player = nil;
}
}
- (void)playbackFailed:(NSNotification *)notification {
AVPlayerItem *item = [notification object];
[item seekToTime:kCMTimeZero]; // item 跳轉到初始
if (item == _playerItem) {
[self resetPlayer];
}
}
KVO 獲取視頻信息, 觀察緩沖進度
觀察 AVPlayerItem 的 status 屬性,當狀態變為 AVPlayerStatusReadyToPlay 時才可以使用。
也可以觀察 loadedTimeRanges 獲取緩沖進度
注冊觀察者
[_playerItem addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew) context:nil]; // 觀察status屬性
監聽觀察者
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
AVPlayerItem *item = (AVPlayerItem *)object;
if ([keyPath isEqualToString:@"status"]) {
AVPlayerStatus status = [[change objectForKey:@"new"] intValue]; // 獲取更改后的狀態
if (status == AVPlayerStatusReadyToPlay) {
CMTime duration = item.duration; // 獲取視頻長度
// 設置視頻時間
[self setMaxDuration:CMTimeGetSeconds(duration)];
// 播放
[self play];
} else if (status == AVPlayerStatusFailed) {
NSLog(@"AVPlayerStatusFailed");
} else {
NSLog(@"AVPlayerStatusUnknown");
}
} else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
NSTimeInterval timeInterval = [self availableDurationRanges]; // 緩沖時間
CGFloat totalDuration = CMTimeGetSeconds(_playerItem.duration); // 總時間
[self.loadedProgress setProgress:timeInterval / totalDuration animated:YES]; // 更新緩沖條
}
}