最近做了一个外包,涉及到一个关于播放器的奇怪需求,刚刚完工,然后打算从最基础开始慢慢实现一个多功能的播放器
Round 1——>基础功能实现
首先,新建一个view继承于UIView,然后此时新建的文件中View的Layer属性还是CALayer
需要把Layer改为AVPlayerLayer类,并且重写set,get方法
在实现文件中添加一下几个方法
/**获取AVPlayerLayer的layer
* @returns 返回AVPlayerLayer对象
*/
+ (Class)layerClass {
return [AVPlayerLayer class];
}
/**重写get方法
*/
- (AVPlayer *)player {
return [(AVPlayerLayer *)[self layer] player];
}
/**重写set方法
*/
- (void)setPlayer:(AVPlayer *)player {
[(AVPlayerLayer *)[self layer] setPlayer:player];
}
在 interface中声明所需要宏,实例变量
#define kTimeLableZreo @"00:00/00:00"
@interface MJPlayerView()
@property (nonatomic,strong) UIView* bottomControlView; //底部控制界面
@property (nonatomic,strong) UISlider* timeProgress; //进度条
@property (nonatomic,strong) UILabel* timeLabel; //时间显示label
@property (nonatomic,strong) UIButton* playBtn; //播放按钮
@property (nonatomic,strong) UIButton* fullScreenBtn; //全屏按钮
@property (nonatomic,strong) AVPlayerItem * playerItem; //AVPlyaer的播放资源
@property (nonatomic,strong) NSTimer* playLabelTime; //获取播放时间的NSTime
@property (nonatomic,strong) NSTimer* sliderTime; //获取进度条时间的NSTime
@end
之后进行界面的布置,直接使用 Masonry 对界面进行布置
#pragma Mark----用代码初始化页面
-(void)initMJPlayerFrame:(CGRect)frame
{
self.backgroundColor = [UIColor blackColor];
//集合底部控件的view,所有底部控件全在该view上
self.bottomControlView = [UIView new];
[self addSubview:self.bottomControlView];
[self.bottomControlView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.mas_offset(UIEdgeInsetsMake(frame.size.height-30, 0, 00, 00));
}];
//添加播放器控件
self.timeProgress = [UISlider new];
self.timeProgress.minimumValue = 0;
self.timeProgress.maximumValue = 1;
[self.timeProgress addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
self.timeProgress.minimumTrackTintColor = [UIColor whiteColor];
self.timeProgress.maximumTrackTintColor = [UIColor grayColor];
[self.timeProgress setThumbImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
[self.timeProgress setThumbImage:[UIImage imageNamed:@"MJPlayer_slider"] forState:UIControlStateHighlighted];
[self.bottomControlView addSubview:self.timeProgress];
[self.timeProgress mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.mas_offset(UIEdgeInsetsMake(0, 40, 0, 40));
}];
//添加播放按钮
self.playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.playBtn setImage:[UIImage imageNamed:@"MJPlayer_play"] forState:UIControlStateNormal];
[self.playBtn setImage:[UIImage imageNamed:@"MJPlayer_pause"] forState:UIControlStateSelected];
[self.playBtn addTarget:self action:@selector(playOrPause:) forControlEvents:UIControlEventTouchUpInside];
[self.bottomControlView addSubview:self.playBtn];
[self.playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.bottomControlView).offset(12);
make.top.equalTo(self.bottomControlView).offset(6);
make.width.equalTo(@(18));
make.height.equalTo(@(20));
}];
//添加全屏按钮
self.fullScreenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.fullScreenBtn setImage:[UIImage imageNamed:@"MJPlayer_fullscreen"] forState:UIControlStateNormal];
[self.fullScreenBtn setImage:[UIImage imageNamed:@"MJPlayer_shrinkscreen"] forState:UIControlStateSelected];
[self.fullScreenBtn addTarget:self action:@selector(fullScreenOrShrinkScreen:) forControlEvents:UIControlEventTouchUpInside];
[self.bottomControlView addSubview:self.fullScreenBtn];
[self.fullScreenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.bottomControlView).offset(-12);
make.top.equalTo(self.bottomControlView).offset(8);
make.width.equalTo(@(15));
make.height.equalTo(@(15));
}];
}
界面完成之后要对AVPlayer进行初始化,主要是对AVPlayerItem
//AVPlyaer的当前播放资源,也就是AVPlayer的currentItem,它包括视频的总时间,播放时间,等各种信息
AVPlayerItem *playerItem;
/**初始化播放器
*
* @param vedioUrlStr 从外部传入的视频url地址
*/
-(void)initMJPlayer:(NSString*)vedioUrlStr
{
NSURL *videoUrl = [NSURL URLWithString:vedioUrlStr];
//playerItem获取视频的信息
self.playerItem = [AVPlayerItem playerItemWithURL:videoUrl];
//给playerItem这个播放资源注册观察,status基本用到两种
//1.AVPlayerStatusReadyToPlay 表示视频已经可以正确播放,
//2.AVPlayerStatusFailed 表示视频初始化失败
[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];
//缓冲已经OK了的监听
[self.playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
//播放完成的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
//将设置好的item赋予player
self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
}
针对已经添加的监听实现对应的方法
#pragma Mark----监听playerItem属性
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
AVPlayerItem *playerItem = (AVPlayerItem *)object;
if ([playerItem status] == AVPlayerStatusReadyToPlay) {
[self listenTimeChange];
} else if ([playerItem status] == AVPlayerStatusFailed) {
//.....
}else 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);
NSLog(@"下载进度:%.2f", timeInterval / totalDuration);
} else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) {
//监听播放器在缓冲数据的状态
} else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
[self.player play];
}
}
控件布局之后,对控件方法进行实现
#pragma Mark----timeProgress滑动停止事件
-(void)sliderChange:(UISlider*)sender
{
CGFloat totalTime = self.playerItem.duration.value / self.playerItem.duration.timescale;
CMTime changedTime = CMTimeMakeWithSeconds(totalTime*sender.value, 1);
[self.player seekToTime:changedTime completionHandler:^(BOOL finished) {
}];
}
#pragma Mark----playBtn播放按钮点击事件
-(void)playOrPause:(UIButton*)sender
{
if (!sender.selected) {
[self.player play];
}else
{
[self.player pause];
}
sender.selected = !sender.selected;
}
#pragma Mark----fullScreenBtn全屏按钮点击事件
-(void)fullScreenOrShrinkScreen:(UIButton*)sender
{
sender.selected = !sender.selected;
if (_mjPlayerViewDelegate&&[_mjPlayerViewDelegate respondsToSelector:@selector(fullScreenOrShrinkScreenDelegate:)]) {
[_mjPlayerViewDelegate fullScreenOrShrinkScreenDelegate:sender];
}
}
#pragma Mark----播放完成的通知
-(void)playFinished:(NSNotification*)notif
{
//未完待续
}
全屏按钮点击使用delegate前往viewController实现
-(void)fullScreenOrShrinkScreenDelegate:(UIButton *)sender
{
if (sender.selected) {
[self.navigationController setNavigationBarHidden:YES];
[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) forKey:@"orientation"];
self.playerView1.frame = CGRectMake(0, 0,kMainScreen_Width ,kMainScreen_Height );
}else
{
[self.navigationController setNavigationBarHidden:NO];
self.playerView1.frame = CGRectMake(0, 0,kMainScreen_Height , kMainScreen_Width/2);
[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait) forKey:@"orientation"];
}
[UIViewController attemptRotationToDeviceOrientation];
}
除了按钮及滑动事件之外,另外一个很重要的元素就是进度条所显示的时间,这边使用label来显示,以下是计算label的显示时间
//监控时间变化
-(void)listenTimeChange
{
__weak typeof (self)self_ = self;
self.playLabelTime = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
CGFloat playTime = self_.player.currentTime.value/self_.player.currentTime.timescale;
CGFloat totalTime = self_.playerItem.duration.value / self_.playerItem.duration.timescale;
CGFloat percent = playTime/totalTime;
self_.timeLabel.text = [NSString stringWithFormat:@"%@/%@",[self_ changeTime:playTime],[self_ changeTime:totalTime]];
self_.timeProgress.value = percent;
}];
}
//时间转换成播放时间
- (NSString *)changeTime:(CGFloat)time{
NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:time];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
if (time/3600 >= 1) {
[formatter setDateFormat:@"HH:mm:ss"];
} else {
[formatter setDateFormat:@"mm:ss"];
}
return [formatter stringFromDate:timeDate];
}
分割线------------------------------------------------------------------------------------------------------------------
未完待续..