CNLivePlayerView.swift
28.5 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//
// CNLivePlayerView.swift
// metaCode
//
// Created by zx on 2023/11/24.
//
import Foundation
import PLPlayerKit
import UIKit
typealias popCallBackBlock = () -> Void
typealias playerPausedCallBackBlock = (_ playerView: CNLivePlayerView) -> Void
typealias playerPlayingCallBackBlock = (_ playerView: CNLivePlayerView) -> Void
typealias playerDidToEndCallBackBlock = (_ playerView: CNLivePlayerView) -> Void
typealias switchAlphaMessageStateCallBackBlock = (_ playerView: CNLivePlayerView) -> Void
typealias switchLockScreenCallBackBlock = (_ playerView: CNLivePlayerView) -> Void
typealias switchInterfaceOrientationCallBackBlock = (_ playerView: CNLivePlayerView) -> Void
let kDSPlayerAnimateTimeInterval = 0.25//动画时间
class CNLivePlayerView:UIView,PLPlayerDelegate{
// MARK: - 播放设置
/// 初始化视频链接地址 为空为停止播放
var playUrl:URL?
/// 视频链接是否为直播
var isLive:Bool = false
// MARK: - 播放属性
/// 是否循环播放(默认NO)
var _isLoopPlay:Bool = false
var isLoopPlay:Bool{
get{
_isLoopPlay
}
set{
_isLoopPlay = newValue
if self.isLive{
return
}
self.player?.loopPlay = _isLoopPlay
}
}
/// 开始播放时间
var startPlayTime:Double = 0.0
/// 获取播放时间
func getPlayTime() -> Double{
return CMTimeGetSeconds(self.player!.currentTime)
}
/// 是否播放完成
var isPlayEnd:Bool = false
/// 是否用户手动暂停
var isUserStop:Bool = false
/// 控制器是否在进行disappear
var _viewControllerIsDisappear:Bool = false
var viewControllerIsDisappear:Bool?{
get{
_viewControllerIsDisappear
}
set{
if (_viewControllerIsDisappear == true && viewControllerIsDisappear == false) {
self.play()
}else if (_viewControllerIsDisappear == false && viewControllerIsDisappear == true) {
self.pauseWithIsRemoveKVOsAndNotifications(isRemove: true)
}
_viewControllerIsDisappear = newValue!
}
}
// MARK: - 回调
/// 点击返回回调
var popCallBack:popCallBackBlock?
/// 播放器暂停回调
var playerPausedCallBack:playerPausedCallBackBlock?
/// 播放器继续播放回调
var playerPlayingCallBack:playerPlayingCallBackBlock?
/// 播放完成回调 如果isLoopPlay==YES,播放完成时请调用stop方法 否则该类释放不掉
var playerDidToEndCallBack:playerDidToEndCallBackBlock?
/// 隐藏/显示视频上面的控件回调
var switchAlphaMessageStateCallBack:switchAlphaMessageStateCallBackBlock?
/// 锁屏/解锁屏回调
var switchLockScreenCallBack:switchLockScreenCallBackBlock?
// MARK: - 预览界面
/// 预览界面 包含视频视图 控件视图
lazy var previewView :UIView = {
let previewView = UIView()
previewView.backgroundColor = .black
previewView.clipsToBounds = true
return previewView
}()
/// 控件视图
lazy var controlView :CNLivePlayerControlView = {
let controlView = CNLivePlayerControlView()
controlView.clickBackBtnAction = {[weak self] in
if self?.controlView.isFullScreen == true{
self?.currentOrientation = .portrait
}else{
self?.popCallBack!()
navigationViewController().popViewController(animated: pushAnimated)
// currentViewController()?.navigationController?.popViewController(animated: pushAnimated)
}
}
controlView.clickFrameBtnAction = {[weak self] in
if self?.controlView.isFullScreen == true{
self?.currentOrientation = .portrait
}else{
self?.currentOrientation = .landscapeRight
}
}
controlView.clickPlayBtnAction = {[weak self] in
self?.isUserStop = false
self?.play()
}
controlView.clickPauseBtnAction = {[weak self] in
self?.isUserStop = true
self?.pauseWithIsRemoveKVOsAndNotifications(isRemove: false)
}
controlView.clickRefreshBtnAction = {[weak self] in
if !(self?.isLocalUrl)! {
showMessage(message: "当前网络不可用")
return
}
self?.play()
}
controlView.switchAlphaMessageStateCallBack = {[weak self] in
if ((self?.switchAlphaMessageStateCallBack?(self!)) != nil){
self?.switchAlphaMessageStateCallBack!(self!)
}
}
controlView.switchLockScreenCallBack = {[weak self] in
if ((self?.switchLockScreenCallBack?(self!)) != nil){
self?.switchLockScreenCallBack!(self!)
}
}
return controlView
}()
// MARK: - 屏幕方向
/// 是否开启检测设备转屏 默认开启
var _isMonitorDeviceOrientation:Bool = true
var isMonitorDeviceOrientation:Bool?{
get{
_isMonitorDeviceOrientation
}
set{
_isMonitorDeviceOrientation = newValue!
self.removeNotification()
self.registerNotification()
}
}
/// 当前屏幕方向
var _currentOrientation: UIDeviceOrientation?
var currentOrientation:UIDeviceOrientation?{
get{
_currentOrientation
}
set{
if (_currentOrientation == newValue ||
newValue == .unknown ||
newValue == .portraitUpsideDown) {
return
}
_currentOrientation = newValue
self.controlView.currentOrientation = _currentOrientation
if (_currentOrientation == .landscapeLeft ||
_currentOrientation == .landscapeRight) {
self.controlView.isFullScreen = true
if self.subviews.contains(self.previewView){
let playerViewRect_onWindow = self.previewView.superview?.convert(self.previewView.frame, to: keyWindow)
self.previewView.frame = playerViewRect_onWindow!
keyWindow?.addSubview(self.previewView)
UIView.animate(withDuration: CGFloat(kDSPlayerAnimateTimeInterval)) {
if (self.currentOrientation == .landscapeLeft) {
self.previewView.transform = CGAffineTransformMakeRotation(-.pi/2)
}else {
self.previewView.transform = CGAffineTransformMakeRotation(.pi/2)
}
self.previewView.frame = CGRect(x: 0, y: 0, width: KSreenWidth, height: KSreenHeight)
self.layoutSubviews()
if (!self.controlView.isAlphaMessage) {
self.controlView.lockBtn!.alpha = 1
}
}
}else{
UIView.animate(withDuration: CGFloat(kDSPlayerAnimateTimeInterval)) {
self.player?.playerView?.transform = CGAffineTransformRotate(self.player!.playerView!.transform, .pi)
self.controlView.transform = CGAffineTransformRotate(self.controlView.transform, .pi)
} completion: { finished in
self.previewView.transform = CGAffineTransformRotate(self.previewView.transform, .pi)
self.player?.playerView?.transform = CGAffineTransformIdentity
self.controlView.transform = CGAffineTransformIdentity
}
}
let landscapeVC = CNLivePlayerLandscapeViewController()
if _currentOrientation == .landscapeLeft{
landscapeVC.interfaceOrientationMask = .landscapeLeft
}else{
landscapeVC.interfaceOrientationMask = .landscapeRight
}
self.fakeWindow!.rootViewController = landscapeVC
}else {
self.controlView.isFullScreen = false
let playerViewRect_onWindow = (self.superview?.convert(self.frame, to: keyWindow))!
UIView.animate(withDuration: CGFloat(kDSPlayerAnimateTimeInterval)) {
self.previewView.transform = CGAffineTransformIdentity
self.player?.playerView?.transform = CGAffineTransformIdentity
self.controlView.transform = CGAffineTransformIdentity
self.previewView.frame = playerViewRect_onWindow
self.layoutSubviews()
self.controlView.lockBtn!.alpha = 0
} completion: { finished in
self.previewView.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height)
self.previewView.removeFromSuperview()
self.insertSubview(self.previewView, at: 0)
}
let landscapeVC = CNLivePlayerLandscapeViewController()
landscapeVC.interfaceOrientationMask = .portrait
self.fakeWindow!.rootViewController = landscapeVC
}
self.switchInterfaceOrientationCallBack!(self)
}
}
/// 修改屏幕方向回调
var switchInterfaceOrientationCallBack:switchInterfaceOrientationCallBackBlock?
//临时window
var _fakeWindow:UIWindow?
var fakeWindow:UIWindow?{
get{
if (_fakeWindow == nil) {
if #available(iOS 13.0, *) {
var windowScene:UIWindowScene? = nil
for scene in UIApplication.shared.connectedScenes {
if scene.activationState == .foregroundActive{
windowScene = scene as? UIWindowScene
}
if ((windowScene == nil) && UIApplication.shared.connectedScenes.count == 1) {
windowScene = scene as? UIWindowScene
}
}
if (windowScene != nil){
_fakeWindow = UIWindow(windowScene: windowScene!)
}else{
_fakeWindow = UIWindow(frame: CGRectZero)
}
}else {
_fakeWindow = UIWindow(frame: CGRectZero)
}
}
return _fakeWindow
}
set{
_fakeWindow = newValue
}
}
//播放器
var player:PLPlayer?
//定时器
var timer:DispatchSourceTimer?
//通知数组
lazy var notifications :NSMutableArray = {
let notifications = NSMutableArray()
return notifications
}()
//KVO数组
lazy var KVOs :NSMutableArray = {
let KVOs = NSMutableArray()
return KVOs
}()
//是否是本地的url
var isLocalUrl:Bool = false
/// 初始化视频
/// @param playUrl 视频链接地址 为空为停止播放
/// @param isLive 是否为直播
// MARK: - 播放设置
func setPlayUrl(playUrl:URL,isLive:Bool){
self.stop()
self.playUrl = playUrl
self.isLive = isLive
if self.playUrl?.scheme == "file"{
self.isLocalUrl = true
}else {
self.isLocalUrl = false
}
self.controlView.coverImageView?.alpha = 1
let option = PLPlayerOption.default()
var format = kPLPLAY_FORMAT_UnKnown
let urlString = self.playUrl?.absoluteString.lowercased()
if urlString!.hasSuffix(".mp4"){
format = kPLPLAY_FORMAT_MP4
}else if urlString!.hasPrefix("rtmp:"){
format = kPLPLAY_FORMAT_FLV
}else if urlString!.hasSuffix(".mp3") {
format = kPLPLAY_FORMAT_MP3
}else if urlString!.hasSuffix(".m3u8") {
format = kPLPLAY_FORMAT_M3U8
}else if urlString!.hasSuffix(".aac") {
format = kPLPLAY_FORMAT_AAC
}
option.setOptionValue(format, forKey: PLPlayerOptionKeyVideoPreferFormat)
option.setOptionValue(kPLLogNone, forKey: PLPlayerOptionKeyLogLevel)
if self.isLive{
self.player = PLPlayer(liveWith: self.playUrl as URL?, option: nil)
self.player?.loopPlay = false
self.controlView.bottomNaviView?.isHidden = false
self.controlView.bottomNaviView?.playBtn?.isHidden = false
self.controlView.bottomNaviView?.progressSlider?.isHidden = true
self.controlView.bottomNaviView?.timeLab?.isHidden = true
self.controlView.bottomNaviView?.frameBtn?.isHidden = false
self.controlView.bottomProgressView?.isHidden = true
}else{
self.player = PLPlayer(url: self.playUrl, option: nil)
self.player!.loopPlay = self.isLoopPlay
self.controlView.bottomNaviView?.isHidden = false
self.controlView.bottomNaviView?.playBtn!.isHidden = false
self.controlView.bottomNaviView?.progressSlider!.isHidden = false
self.controlView.bottomNaviView?.timeLab!.isHidden = false
self.controlView.bottomNaviView!.frameBtn!.isHidden = false
self.controlView.bottomProgressView!.isHidden = false
}
self.controlView.player = self.player
self.controlView.isLive = self.isLive
self.player!.delegateQueue = DispatchQueue.main
self.player!.delegate = self
self.player!.rotationMode = .noRotation
self.player!.playerView!.contentMode = .scaleAspectFit
self.player!.playerView!.backgroundColor = .black
self.previewView.insertSubview(self.player!.playerView!, at: 0)
self.layoutSubviews()
}
/// 结束播放 如果isLoopPlay==YES,播放完成时请调用stop方法 否则该类释放不掉
func stop(){
if self.player?.playerView?.superview != nil{
self.player?.playerView?.removeFromSuperview()
}
self.player?.stop()
self.resetUIProperty()
self.removeKVOsAndNotifications()
}
/// 暂停播放
/// @param isRemove 是否删除kvo、通知、定时器
func pauseWithIsRemoveKVOsAndNotifications(isRemove:Bool){
self.player?.pause()
if isRemove{
self.removeKVOsAndNotifications()
}
}
// MARK: - 播放状态
/// 开始/继续播放
func play(){
// if (![DSCommonManager sharedManager].isAllowPlayVideo) {
// DS_showMessage(@"暂时无法播放视频");
// return;
// }
if (self.player!.status == .statusPlaying) {
return
}
if (self.playUrl == nil) {
return
}
self.controlView.failureView?.isHidden = true
self.registerNotification()
self.initTimer()
self.controlView.gestureView?.private_style = .nonePrivate
self.controlView.bottomNaviView?.progressSlider?.isUserInteractionEnabled = true
if (self.player!.status == .statusPaused) {
self.player?.resume()
}else {
self.player?.play()
}
}
// MARK: - 定时器
func initTimer(){
self.invalidateTimer()
let timeInterval = 0.01
self.timer = CNLiveTimer.bk_setupTimerWithTimeInterval(timeInterval: timeInterval, totalTime: kBKTimerRepeatsTime, handler: { [weak self] timer, lastTime in
self?.controlView.timerTriggeringMethod(timeInterval: timeInterval)
})
}
func invalidateTimer(){
if self.timer != nil{
CNLiveTimer.bk_removeTimer(timer: self.timer!)
}
}
// MARK: - 初始化界面
func resetUIProperty(){
self.playUrl = nil
self.controlView.bottomNaviView?.playBtn?.isHidden = true
self.controlView.bottomNaviView?.progressSlider?.isHidden = true
self.controlView.bottomNaviView?.progressSlider?.value = 0
self.controlView.bottomNaviView?.progressSlider?.bufferValue = 0
self.controlView.bottomNaviView?.timeLab?.isHidden = true
self.controlView.bottomNaviView?.timeLab?.text = "00:00/00:00"
self.controlView.bottomNaviView?.timeStyle = .MM_SS
self.controlView.bottomNaviView?.frameBtn?.isHidden = true
self.controlView.bottomNaviView?.isHidden = true
self.controlView.bottomProgressView?.value = 0
self.controlView.bottomProgressView?.bufferValue = 0
self.controlView.gestureView?.style = .none
}
// MARK: - 删除kvo、通知、定时器
func removeKVOsAndNotifications(){
self.controlView.loadingView?.stopAnimate()
self.removeNotification()
self.invalidateTimer()
}
// MARK: - init
init() {
super.init(frame: CGRectZero)
self.initializeThings()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initializeThings()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initializeThings(){
self.isMonitorDeviceOrientation = true
self.backgroundColor = .black
self.initUI()
}
deinit {
self.stop()
for obj in self.subviews{
obj.removeFromSuperview()
}
self.removeFromSuperview()
}
// MARK: - layoutSubviews
override func layoutSubviews() {
super.layoutSubviews()
if self.subviews.contains(self.previewView){
self.previewView.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height)
}
self.player?.playerView?.frame = CGRect(x: 0, y: 0, width: self.previewView.bounds.size.width, height: self.previewView.bounds.size.height)
self.controlView.frame = CGRect(x: 0, y: 0, width: self.previewView.bounds.size.width, height: self.previewView.bounds.size.height)
}
// MARK: - initUI
func initUI(){
self.addSubview(self.previewView)
self.previewView.addSubview(self.controlView)
}
// MARK: - PLPlayerDelegate
/**
告知代理对象播放器状态变更
*/
func player(_ player: PLPlayer, statusDidChange state: PLPlayerStatus) {
DispatchQueue.main.async {
switch (state){
case .statusUnknow:break
case .statusOpen:
self.controlView.loadingView?.stopAnimate()
break
case .statusPreparing:
self.controlView.loadingView?.startAnimate()
self.controlView.bottomNaviView?.isUserInteractionEnabled = false
break
case .statusReady:
self.controlView.loadingView?.startAnimate()
break
case .statusCaching:
self.controlView.loadingView?.startAnimate()
break
case .statusPlaying:
self.controlView.loadingView?.stopAnimate()
self.isPlayEnd = false
self.controlView.coverImageView?.alpha = 0
self.controlView.bottomNaviView?.isUserInteractionEnabled = true
self.controlView.circlePlayBtn?.setBackgroundImage(UIImage(named: "DS_player_circle_pause"), for: .normal)
self.controlView.bottomNaviView?.playImageView!.image = UIImage(named: "DS_player_pause")
if ((self.playerPlayingCallBack?(self)) != nil){
self.playerPlayingCallBack!(self)
}
if self.startPlayTime > 0{
self.controlView.loadingView?.startAnimate()
self.player?.seek(to: CMTime(value: CMTimeValue(Int(self.startPlayTime)*30), timescale: 30))
self.startPlayTime = 0
}
break
case .statusPaused:
self.controlView.loadingView?.stopAnimate()
self.controlView.circlePlayBtn?.setBackgroundImage(UIImage(named: "DS_player_circle_start"), for: .normal)
self.controlView.bottomNaviView?.playImageView!.image = UIImage(named: "DS_player_start")
if ((self.playerPausedCallBack?(self)) != nil){
self.playerPausedCallBack!(self)
}
break
case .statusStopped:
self.controlView.loadingView?.stopAnimate()
break
case .statusError:
self.controlView.loadingView?.stopAnimate()
break
case .stateAutoReconnecting:
self.controlView.loadingView?.startAnimate()
break
case .statusCompleted:
self.controlView.loadingView?.stopAnimate()
self.isPlayEnd = true
self.controlView.circlePlayBtn?.setBackgroundImage(UIImage(named: "DS_player_circle_start"), for: .normal)
self.controlView.bottomNaviView?.playImageView!.image = UIImage(named: "DS_player_start")
self.controlView.gestureView?.private_style = .none
self.controlView.bottomNaviView?.progressSlider?.isUserInteractionEnabled = false
if ((self.playerDidToEndCallBack?(self)) != nil){
self.playerDidToEndCallBack!(self)
}
break
@unknown default: break
}
}
}
/**
告知代理对象播放器因错误停止播放
*/
func player(_ player: PLPlayer, stoppedWithError error: Error?) {
DispatchQueue.main.async { [weak self] in
self?.controlView.loadingView?.stopAnimate()
let delayTime = DispatchTime.now()
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self?.controlView.failureView?.isHidden = false
if (self?.isLocalUrl == nil || self?.isLocalUrl == false){
//if (!self.isLocalUrl && [DSNetworkRequest shareClient].netStatus == DSNetworkStatusNotReachable)
self?.controlView.failureView?.errorMessage = "当前网络不可用,请检查网络后重试"
}else{
self?.controlView.failureView?.errorMessage = "视频加载失败"
}
}
}
}
/**
点播已缓冲区域
*/
func player(_ player: PLPlayer, loadedTimeRange timeRange: CMTime) {
DispatchQueue.main.async {
let totalSecond = CMTimeGetSeconds(self.player!.totalDuration)
if totalSecond > 0{
let bufferSecond = CMTimeGetSeconds(timeRange)
self.controlView.bottomNaviView?.progressSlider?.bufferValue = bufferSecond / totalSecond
}else{
self.controlView.bottomNaviView?.progressSlider?.bufferValue = 0
}
self.controlView.bottomProgressView?.bufferValue = self.controlView.bottomNaviView!.progressSlider!.bufferValue
}
}
/**
seekTo 完成的回调通知
*/
func player(_ player: PLPlayer, seekToCompleted isCompleted: Bool) {
DispatchQueue.main.async {
self.controlView.loadingView?.stopAnimate()
}
}
func registerNotification(){
self.removeNotification()
/*
[[DSCommonManager sharedManager] addObserver:self forKeyPath:@"netStatus" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];//网络状态
DSPlayerKVOModel * model = [[DSPlayerKVOModel alloc] init];
model.obj = [DSCommonManager sharedManager];
model.path = @"netStatus";
[self.KVOs addObject:model];
[[DSCommonManager sharedManager] addObserver:self forKeyPath:@"isAllowPlayVideo" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];//不允许播放视频
DSPlayerKVOModel * model1 = [[DSPlayerKVOModel alloc] init];
model1.obj = [DSCommonManager sharedManager];
model1.path = @"isAllowPlayVideo";
[self.KVOs addObject:model1];
*/
if self.isMonitorDeviceOrientation!{
self.addNotificationWithSelector(aSelector: #selector(deviceOrientationDidChangeNotification), aName: UIDevice.orientationDidChangeNotification)//转屏通知
}
self.addNotificationWithSelector(aSelector: #selector(audioSessionRouteChangeNotification), aName: AVAudioSession.routeChangeNotification)//播放设备切换通知
self.addNotificationWithSelector(aSelector: #selector(willResignActiveNotification), aName: UIApplication.willResignActiveNotification)//出app
self.addNotificationWithSelector(aSelector: #selector(didBecomeActiveNotification), aName: UIApplication.didBecomeActiveNotification)//回app
}
func addNotificationWithSelector(aSelector:Selector,aName:Notification.Name){
NotificationCenter.default.addObserver(self, selector: aSelector, name: aName, object: nil)
self.notifications.add(aName)
}
func removeNotification(){
for kvoMdl in self.KVOs {
let kvoModel = kvoMdl as! CNLivePlayerKVOModel
kvoModel.obj?.removeObserver(self, forKeyPath: kvoModel.path!)
}
self.KVOs.removeAllObjects()
for tempNotificationName in self.notifications {
let notificationName = tempNotificationName as! Notification.Name
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)
}
self.notifications.removeAllObjects()
}
/**
转屏通知
*/
@objc func deviceOrientationDidChangeNotification(){
DispatchQueue.main.async {
//查看设备方向
var currentOrientation = UIDevice.current.orientation
//设备方向和屏幕方向一直不操作 设备方向为倒向不操作 锁屏且屏幕方向为正不操作
if (self.currentOrientation == currentOrientation || currentOrientation == .portraitUpsideDown ||
(self.controlView.isLockScreen && currentOrientation == .portrait)) {
return
}
//修改
self.currentOrientation = currentOrientation
}
}
/**
播放设备切换通知
*/
@objc func audioSessionRouteChangeNotification(notification:Notification){
DispatchQueue.main.async {
let reasonValue = notification.userInfo![AVAudioSessionRouteChangeReasonKey] as? Int
//TODO 不知道转成功没有
let reason = Int(reasonValue ?? 0)
if reason == AVAudioSession.RouteChangeReason.oldDeviceUnavailable.rawValue{
//耳机拔出停止播放
self.pauseWithIsRemoveKVOsAndNotifications(isRemove: false)
}
}
}
/**
去后台
*/
@objc func willResignActiveNotification(){
DispatchQueue.main.async {
self.pauseWithIsRemoveKVOsAndNotifications(isRemove: false)
}
}
/**
回来
*/
@objc func didBecomeActiveNotification(){
DispatchQueue.main.async {
if !self.isUserStop && !self.isPlayEnd{
self.play()
self.setNeedsLayout()
}
}
}
// MARK: - KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
/*
if (!self.isLocalUrl && [keyPath isEqualToString:@"netStatus"]) {
DSNetworkStatus lastNetworkStatus = [change[@"old"] integerValue];
DSNetworkStatus currentNetworkStatus = [change[@"new"] integerValue];
if (lastNetworkStatus == currentNetworkStatus) {
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
if (currentNetworkStatus != DSNetworkStatusNotReachable) {
if (!self.isUserStop && !self.isPlayEnd) {
[self play];
}
}else {
DS_showMessage(@"网络好像断开了~");
}
});
}else if ([keyPath isEqualToString:@"isAllowPlayVideo"]) {
BOOL flag = [change[@"new"] integerValue];
dispatch_async(dispatch_get_main_queue(), ^{
if (flag == NO) {
[self pauseWithIsRemoveKVOsAndNotifications:NO];
}
});
}*/
}
// MARK: - 退出全屏
/// 退出全屏
func exitFullScreen(){
self.controlView.resetHideTime()
if self.controlView.isFullScreen!{
self.currentOrientation = .portrait
}
}
}