前言
最近在项目中,遇到了视频播放的需求,直接使用系统封装的播放器太过于简单,不能很好的满足项目要求,于是花时间研究了一下,使用AVPlayer
来自定义播放器。
本视频播放器主要自定义了带缓冲显示的进度条,可以拖动调节视频播放进度的播放条,具有当前播放时间和总时间的Label,全屏播放功能,定时消失的工具条。播放器已经封装到UIView
中,支持自动旋转切换全屏,支持UITableView
。
作为一个开发者,有一个学习的氛围跟一个交流圈子特别重要,这是一个我的iOS交流群:812157648,不管你是小白还是大牛欢迎入驻 ,分享BAT,阿里面试题、面试经验,讨论技术, 大家一起交流学习成长!
主要功能
1.带缓冲显示的进度条
在自定义的时候,主要是需要计算当前进度和监听缓冲的进度,细节方面需要注意进度颜色,进度为0的时候要设置为透明色,缓冲完成的时候需要设置颜色,不然全屏切换就会导致缓冲完成的进度条颜色消失。
- 自定义进度条的代码
#pragma mark - 创建UIProgressView
- (void)createProgress
{
CGFloat width;
if (_isFullScreen == NO)
{
width = self.frame.size.width;
}
else
{
width = self.frame.size.height;
}
_progress = [[UIProgressView alloc]init];
_progress.frame = CGRectMake(_startButton.right + Padding, 0, width - 80 - Padding - _startButton.right - Padding - Padding, Padding);
_progress.centerY = _bottomView.height/2.0;
//进度条颜色
_progress.trackTintColor = ProgressColor;
// 计算缓冲进度
NSTimeInterval timeInterval = [self availableDuration];
CMTime duration = _playerItem.duration;
CGFloat totalDuration = CMTimeGetSeconds(duration);
[_progress setProgress:timeInterval / totalDuration animated:NO];
CGFloat time = round(timeInterval);
CGFloat total = round(totalDuration);
//确保都是number
if (isnan(time) == 0 && isnan(total) == 0)
{
if (time == total)
{
//缓冲进度颜色
_progress.progressTintColor = ProgressTintColor;
}
else
{
//缓冲进度颜色
_progress.progressTintColor = [UIColor clearColor];
}
}
else
{
//缓冲进度颜色
_progress.progressTintColor = [UIColor clearColor];
}
[_bottomView addSubview:_progress];
}
- 缓冲进度计算和监听代码
#pragma mark - 缓存条监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"loadedTimeRanges"])
{
// 计算缓冲进度
NSTimeInterval timeInterval = [self availableDuration];
CMTime duration = _playerItem.duration;
CGFloat totalDuration = CMTimeGetSeconds(duration);
[_progress setProgress:timeInterval / totalDuration animated:NO];
//设置缓存进度颜色
_progress.progressTintColor = ProgressTintColor;
}
}
2.可以拖动调节视频播放进度的播放条
这里主要需要注意的是创建的播放条需要比进度条稍微长一点,这样才可以看到滑块从开始到最后走完整个进度条。播放条最好单独新建一个继承自UISlider
的控件,因为进度条和播放条的大小很可能不能完美的重合在一起,这样看起来就会有2条线条&