引入头文件
#import<AVFoundation/AVFoundation.h>
定义三个属性
@property (nonatomic,strong) AVPlayer *player;
@property (nonatomic,strong) AVPlayerLayer *playerLayer;
@property (nonatomic,strong) AVPlayerItem *playerItem;
初始化播放器
// 1、创建AVPlayerItem
_playerItem = [AVPlayerItem playerItemWithURL:sourceMovieURL];
// 2、根据AVPlayerItem创建媒体播放器
_player = [AVPlayer playerWithPlayerItem:_playerItem];
// 3、创建AVPlayerLayer,用于呈现视频
_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
// 4、设置显示大小和位置
_playerLayer.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
// 5、设置拉伸模式
_playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
// 6、获取播放持续时间
NSLog(@"%lld", _playerItem.duration.value);
[self.layer addSublayer:_playerLayer];
// 播放1s回调一次
[_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
}];
播放和暂停的控制
- (void)clickPlayBtn {
//当视频加载成功时
if (_player && _player.currentItem.status == AVPlayerStatusReadyToPlay) {
//rate为0表示是暂停状态
if (_player.rate == 0) {
[self.toolsView.PlayButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
if (self.isEnd) {
[self.player seekToTime:CMTimeMakeWithSeconds(0, NSEC_PER_SEC) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];//播放结束后,点击播放从头开始重新播放
}
[_player play];//开始播放
}else {
[_player pause];//暂停播放
[self.toolsView.PlayButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
}
}
}
使用kvo监听播放器准备状态和缓冲状态
- (void)addKVOObserver {
[_playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
[_playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
AVPlayerItem *playerItem = (AVPlayerItem *)object;
if ([keyPath isEqualToString:@"status"]) {
if ([playerItem status] == AVPlayerStatusReadyToPlay) {
NSLog(@"AVPlayerStatusReadyToPlay");
self.toolsView.PlayButton.enabled = YES;
CMTime duration = self.playerItem.duration;// 获取视频总长度
self.totalSeconds = [self getTimeToSeconds:duration];
self.toolsView.totalTimeLabel.text = [self secondsToString:self.totalSeconds];
} else if ([playerItem status] == AVPlayerStatusFailed) {
NSLog(@"AVPlayerStatusFailed");//视频源初始化失败
}
} else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
NSLog(@"已缓冲:%f",timeInterval);
CMTime duration = self.playerItem.duration;
CGFloat totalDuration = CMTimeGetSeconds(duration);
[self.toolsView.loadProgressView setProgress:timeInterval / totalDuration animated:YES];
}
}
监听播放结束
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
- (void)playbackFinished:(NSNotification *)noti {
NSLog(@"播放结束");
[self.toolsView.PlayButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
self.toolsView.slider.value = 0;
self.isEnd = YES;
self.toolsView.currentTimeLabel.text = @"00:00";
}
下面是几个用到的工具方法
- (CGFloat)getTimeToSeconds:(CMTime)time {
CGFloat second = time.value / time.timescale;// 转换成秒
return second;
}
- (NSString *)secondsToString:(CGFloat)seconds {
NSNumber *num = [NSNumber numberWithFloat:seconds];
int sec = [num intValue] % 60;
NSString *secStr = [NSString stringWithFormat:@"%d",sec];
if (sec<10) {
secStr = [NSString stringWithFormat:@"0%d",sec];
}
int min = [num intValue] / 60;
NSString *minStr = [NSString stringWithFormat:@"%d",min];
if (min<10) {
minStr = [NSString stringWithFormat:@"0%d",min];
}
NSString *resultString = [NSString stringWithFormat:@" %@:%@ ",minStr,secStr];
return resultString;
}
- (NSTimeInterval)availableDuration{
NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
return result;
}
调用方式
self.playerView = [[PlayerView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200)];
[self.view addSubview:self.playerView];
self.playerView.sourcePath = path;//本地文件路径或者http网络路径都行
具体使用方式可以参考https://github.com/zjl0624/CZPlayer