iOS 基于AVPlayer封装的播放器,全屏切换,切换播放源

效果图:自定义视频播放器.gif

看了一些githupstar比较多的一些播放器,比如ZFPlayer,CLPlayer。关于全屏切换以及切换播放源的实现基本一样,但是在全屏切换ZFPlayer实现不是很好。
ZFPlayer关闭了当前控制器的旋转属性才可以旋转。代码片段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 返回值要必须为NO
- (BOOL)shouldAutorotate {
return NO;
}
- (UIStatusBarStyle)preferredStatusBarStyle {
// 这里设置横竖屏不同颜色的statusbar
// if (ZFPlayerShared.isLandscape) {
// return UIStatusBarStyleDefault;
// }
return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden {
return ZFPlayerShared.isStatusBarHidden;
}

如果shouldAutorotate返回为YES,全屏切换就会出问题。

CLPlayer的作者提供了一种思路,当页面可以进行旋转的时候,直接利用KVC设置旋转即可.

1
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];

当页面不可以旋转的时候,可以旋转当前视图。

1
2
3
4
5
6
7
8
9
10
11
12
//播放器所在控制器不支持旋转,采用旋转view的方式实现
if (oriention == UIInterfaceOrientationLandscapeLeft){
[UIView animateWithDuration:0.25 animations:^{
self.transform = CGAffineTransformMakeRotation(M_PI / 2);
}];
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
}else if (oriention == UIInterfaceOrientationLandscapeRight) {
[UIView animateWithDuration:0.25 animations:^{
self.transform = CGAffineTransformMakeRotation( - M_PI / 2);
}];
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft animated:NO];
}

#####补充一点:当前页面旋转以及不可旋转有一个区别:旋转的方向是相反的,需要我们做个判断:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if (orientation == UIDeviceOrientationLandscapeLeft) {
if (self.isLandScape) {
//因为受控制器的影响是反的
[self setOrientationLandscapeConstraint:UIInterfaceOrientationLandscapeRight];
}else{
[self setOrientationLandscapeConstraint:UIInterfaceOrientationLandscapeLeft];
}
}else if (orientation == UIDeviceOrientationLandscapeRight){
if (self.isLandScape) {
[self setOrientationLandscapeConstraint:UIInterfaceOrientationLandscapeLeft];
}else{
[self setOrientationLandscapeConstraint:UIInterfaceOrientationLandscapeRight];
}

之前都是使用使用私有的API进行旋转,可以了解一下,尽管可以上架,当时有一定的风险:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val = UIInterfaceOrientationLandscapeRight;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}

因为私有API的风险,所以基本上在切换横屏的时候,当前播放器是加在keyWindow上的。

关于切换播放源,我们只需要移除当前playerItem的通知、观察者,重置播放器即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
-(void)setCurrentModel:(LXPlayModel *)currentModel{
_currentModel = currentModel;
self.contollView.playTitle = _currentModel.videoTitle;
[self addPlayerToFatherView:_currentModel.fatherView];
//播放前准备
[self readyToPlay];
}
#pragma mark---播放前的准备--
-(void)readyToPlay{
self.backgroundColor = [UIColor blackColor];
self.playerItem =[AVPlayerItem playerItemWithAsset:[AVAsset assetWithURL:[NSURL URLWithString:self.currentModel.playUrl]]];
[self.contollView showLoadingAnimation:YES];
}
-(void)setPlayerItem:(AVPlayerItem *)playerItem{
if (_playerItem) {
//移除观察者
[self removeObserver];
//重置播放器
[self resetPlayer];
self.panRecognizer.enabled = NO;
}
_playerItem = playerItem;
self.player =[AVPlayer playerWithPlayerItem:_playerItem];
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
//设置静音模式播放声音
// AVAudioSession * session = [AVAudioSession sharedInstance];
// [session setCategory:AVAudioSessionCategoryPlayback error:nil];
// [session setActive:YES error:nil];
[self addNotificationAndObserver];
}
#pragma mark--重置播放器---
-(void)resetPlayer{
self.playState = LXPlayerStateStopped;
self.isEnd = NO;
[self.playerLayer removeFromSuperlayer];
self.player = nil;
[self.contollView resetPlayState];
[self recoveryHideSelector];
}

关于单击显示以及双击暂停播放,处理如下:

1
2
3
4
5
6
// 解决点击当前view时候响应其他控件事件
[self.singleTap setDelaysTouchesBegan:YES];
[self.doubleTap setDelaysTouchesBegan:YES];
// 双击失败响应单击事件
[self.singleTap requireGestureRecognizerToFail:self.doubleTap];

我们需要开启定时器显示以及隐藏控制层,但是当有手势或者触摸作用在播放器的时候,会和定时器冲突。我们需要的是在当前屏幕接收事件的时候定时器不起作用,所有需要在接收手势的地方做处理,5秒后用户没有操作恢复定时器,时间可以自己设定:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
if (touch.view) {
[self cancelHideSelector];
[self recoveryHideSelector];
}
return YES;
}

1
2
3
4
5
6
7
8
9
#pragma mark--恢复定时器--
-(void)recoveryHideSelector{
[self performSelector:@selector(hideControllView) withObject:nil afterDelay:5];
}
#pragma mark---取消定时器
-(void)cancelHideSelector{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideControllView) object:nil];
}

关于全屏处理屏幕亮度和音量还是借鉴上面两个播放器,代码几乎都一样,就不多说了。

还有一点:ZFPlayer,CLPlayer 并没有对slider做处理。我们经常会看到播放器,点击slider会快进到某个进度,或者slider会有一个平移手势,以此来快进快退。所以我也对slider做了处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//slide平移手势的回调
self.contollView.panBegin = ^{
weakSelf.isDragged = YES;
if (!weakSelf.contollView) {
weakSelf.contollView.isShow = YES;
}
[weakSelf cancelHideSelector];
};
self.contollView.getSlideValue = ^(CGFloat value) {
// 当前frame宽度 * 总时长 / 总frame长度 = 当前时间
CGFloat duration = CMTimeGetSeconds([weakSelf.player.currentItem duration]);
int time = duration * value;
// 更新时间
weakSelf.contollView.startTime = [LXAVPlayView durationStringWithTime:(NSInteger) time];
};
self.contollView.panEnd = ^(CGFloat value) {
CGFloat duration = CMTimeGetSeconds([weakSelf.player.currentItem duration]);
int time = duration * value;
weakSelf.isDragged = YES;
[weakSelf seekToTime:time completionHandler:nil];
};
self.contollView.tapSlider = ^(CGFloat value) {
// 当前frame宽度 * 总时长 / 总frame长度 = 当前时间
weakSelf.isDragged = YES;
CGFloat duration = CMTimeGetSeconds([weakSelf.player.currentItem duration]);
int time = duration * value;
// 更新时间
weakSelf.contollView.startTime = [LXAVPlayView durationStringWithTime:(NSInteger) time];
[weakSelf seekToTime:time completionHandler:nil];
};

关于播放器的释放,本来是打算移除通知,置空player全部放在dellloc中,结果发现返回的时候播放器会延迟销毁。所以就把销毁播放器放在当前页面即将消失的时候。

1
2
3
4
5
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self.playerview destroyPlayer];
}

最后

注意点基本上已经介绍完了,因为不太喜欢delegate的冗余,所以代码中基本上都使用了block回调,本意是希望代码简洁一点,结果发现代码量依旧不少。

demo 地址: LXPlayer

推荐一个技术博客:https://4xx.me/