ZXVideoPlayerController.m 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. //
  2. // ZXVideoPlayerController.m
  3. // ZXVideoPlayer
  4. //
  5. // Created by Shawn on 16/4/21.
  6. // Copyright © 2016年 Shawn. All rights reserved.
  7. //
  8. #import "ZXVideoPlayerController.h"
  9. #import "ZXVideoPlayerControlView.h"
  10. #import <AVFoundation/AVFoundation.h>
  11. typedef NS_ENUM(NSInteger, ZXPanDirection){
  12. ZXPanDirectionHorizontal, // 横向移动
  13. ZXPanDirectionVertical, // 纵向移动
  14. };
  15. /// 播放器显示和消失的动画时长
  16. static const CGFloat kVideoPlayerControllerAnimationTimeInterval = 0.3f;
  17. @interface ZXVideoPlayerController () <UIGestureRecognizerDelegate>
  18. /// 播放器视图
  19. @property (nonatomic, strong) ZXVideoPlayerControlView *videoControl;
  20. /// 是否已经全屏模式
  21. @property (nonatomic, assign) BOOL isFullscreenMode;
  22. /// 是否锁定
  23. @property (nonatomic, assign) BOOL isLocked;
  24. /// 设备方向
  25. @property (nonatomic, assign, readonly, getter=getDeviceOrientation) UIDeviceOrientation deviceOrientation;
  26. /// player duration timer
  27. @property (nonatomic, strong) NSTimer *durationTimer;
  28. /// pan手势移动方向
  29. @property (nonatomic, assign) ZXPanDirection panDirection;
  30. /// 快进退的总时长
  31. @property (nonatomic, assign) CGFloat sumTime;
  32. /// 是否在调节音量
  33. @property (nonatomic, assign) BOOL isVolumeAdjust;
  34. /// 系统音量slider
  35. @property (nonatomic, strong) UISlider *volumeViewSlider;
  36. @end
  37. @implementation ZXVideoPlayerController
  38. #pragma mark - life cycle
  39. - (void)dealloc
  40. {
  41. [[NSNotificationCenter defaultCenter] removeObserver:self];
  42. }
  43. - (instancetype)initWithFrame:(CGRect)frame
  44. {
  45. self = [super init];
  46. if (self) {
  47. self.view.frame = frame;
  48. self.view.backgroundColor = [UIColor blackColor];
  49. self.controlStyle = MPMovieControlStyleNone;
  50. [self.view addSubview:self.videoControl];
  51. self.videoControl.frame = self.view.bounds;
  52. UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panDirection:)];
  53. pan.delegate = self;
  54. [self.videoControl addGestureRecognizer:pan];
  55. [self configObserver];
  56. [self configControlAction];
  57. [self configDeviceOrientationObserver];
  58. [self configVolume];
  59. }
  60. return self;
  61. }
  62. #pragma mark -
  63. #pragma mark - UIGestureRecognizerDelegate
  64. -(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch
  65. {
  66. // UISlider & UIButton & topBar 不需要响应手势
  67. if([touch.view isKindOfClass:[UISlider class]] || [touch.view isKindOfClass:[UIButton class]] || [touch.view.accessibilityIdentifier isEqualToString:@"TopBar"]) {
  68. return NO;
  69. } else {
  70. return YES;
  71. }
  72. }
  73. #pragma mark -
  74. #pragma mark - Public Method
  75. /// 展示播放器
  76. - (void)showInView:(UIView *)view
  77. {
  78. if ([UIApplication sharedApplication].statusBarStyle != UIStatusBarStyleLightContent) {
  79. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
  80. }
  81. [view addSubview:self.view];
  82. self.view.alpha = 0.0;
  83. [UIView animateWithDuration:kVideoPlayerControllerAnimationTimeInterval animations:^{
  84. self.view.alpha = 1.0;
  85. } completion:^(BOOL finished) {}];
  86. if (self.getDeviceOrientation == UIDeviceOrientationLandscapeLeft || self.getDeviceOrientation == UIDeviceOrientationLandscapeRight) {
  87. [self changeToOrientation:self.getDeviceOrientation];
  88. } else {
  89. [self changeToOrientation:UIDeviceOrientationPortrait];
  90. }
  91. }
  92. #pragma mark -
  93. #pragma mark - Private Method
  94. /// 控件点击事件
  95. - (void)configControlAction
  96. {
  97. [self.videoControl.playButton addTarget:self action:@selector(playButtonClick) forControlEvents:UIControlEventTouchUpInside];
  98. [self.videoControl.pauseButton addTarget:self action:@selector(pauseButtonClick) forControlEvents:UIControlEventTouchUpInside];
  99. [self.videoControl.fullScreenButton addTarget:self action:@selector(fullScreenButtonClick) forControlEvents:UIControlEventTouchUpInside];
  100. [self.videoControl.shrinkScreenButton addTarget:self action:@selector(shrinkScreenButtonClick) forControlEvents:UIControlEventTouchUpInside];
  101. [self.videoControl.lockButton addTarget:self action:@selector(lockButtonClick:) forControlEvents:UIControlEventTouchUpInside];
  102. [self.videoControl.backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
  103. // slider
  104. [self.videoControl.progressSlider addTarget:self action:@selector(progressSliderValueChanged:) forControlEvents:UIControlEventValueChanged];
  105. [self.videoControl.progressSlider addTarget:self action:@selector(progressSliderTouchBegan:) forControlEvents:UIControlEventTouchDown];
  106. [self.videoControl.progressSlider addTarget:self action:@selector(progressSliderTouchEnded:) forControlEvents:UIControlEventTouchUpInside];
  107. [self.videoControl.progressSlider addTarget:self action:@selector(progressSliderTouchEnded:) forControlEvents:UIControlEventTouchUpOutside];
  108. [self.videoControl.progressSlider addTarget:self action:@selector(progressSliderTouchEnded:) forControlEvents:UIControlEventTouchCancel];
  109. [self setProgressSliderMaxMinValues];
  110. [self monitorVideoPlayback];
  111. }
  112. /// 开始播放时根据视频文件长度设置slider最值
  113. - (void)setProgressSliderMaxMinValues
  114. {
  115. CGFloat duration = self.duration;
  116. self.videoControl.progressSlider.minimumValue = 0.f;
  117. self.videoControl.progressSlider.maximumValue = floor(duration);
  118. }
  119. /// 监听播放进度
  120. - (void)monitorVideoPlayback
  121. {
  122. double currentTime = floor(self.currentPlaybackTime);
  123. double totalTime = floor(self.duration);
  124. // 更新时间
  125. [self setTimeLabelValues:currentTime totalTime:totalTime];
  126. // 更新播放进度
  127. self.videoControl.progressSlider.value = ceil(currentTime);
  128. // 更新缓冲进度
  129. self.videoControl.bufferProgressView.progress = self.playableDuration / self.duration;
  130. // if (self.duration == self.playableDuration && self.playableDuration != 0.0) {
  131. // NSLog(@"缓冲完成");
  132. // }
  133. // int percentage = self.playableDuration / self.duration * 100;
  134. // NSLog(@"缓冲进度: %d%%", percentage);
  135. }
  136. /// 更新播放时间显示
  137. - (void)setTimeLabelValues:(double)currentTime totalTime:(double)totalTime {
  138. double minutesElapsed = floor(currentTime / 60.0);
  139. double secondsElapsed = fmod(currentTime, 60.0);
  140. NSString *timeElapsedString = [NSString stringWithFormat:@"%02.0f:%02.0f", minutesElapsed, secondsElapsed];
  141. double minutesRemaining = floor(totalTime / 60.0);
  142. double secondsRemaining = floor(fmod(totalTime, 60.0));
  143. NSString *timeRmainingString = [NSString stringWithFormat:@"%02.0f:%02.0f", minutesRemaining, secondsRemaining];
  144. self.videoControl.timeLabel.text = [NSString stringWithFormat:@"%@/%@",timeElapsedString,timeRmainingString];
  145. }
  146. /// 开启定时器
  147. - (void)startDurationTimer
  148. {
  149. if (self.durationTimer) {
  150. [self.durationTimer setFireDate:[NSDate date]];
  151. } else {
  152. self.durationTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(monitorVideoPlayback) userInfo:nil repeats:YES];
  153. [[NSRunLoop currentRunLoop] addTimer:self.durationTimer forMode:NSRunLoopCommonModes];
  154. }
  155. }
  156. /// 暂停定时器
  157. - (void)stopDurationTimer
  158. {
  159. if (_durationTimer) {
  160. [self.durationTimer setFireDate:[NSDate distantFuture]];
  161. }
  162. }
  163. /// MARK: 播放器状态通知
  164. /// 监听播放器状态通知
  165. - (void)configObserver
  166. {
  167. // 播放状态改变,可配合playbakcState属性获取具体状态
  168. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMPMoviePlayerPlaybackStateDidChangeNotification) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
  169. // 媒体网络加载状态改变
  170. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMPMoviePlayerLoadStateDidChangeNotification) name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
  171. // 视频显示状态改变
  172. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMPMoviePlayerReadyForDisplayDidChangeNotification) name:MPMoviePlayerReadyForDisplayDidChangeNotification object:nil];
  173. // 确定了媒体播放时长后
  174. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMPMovieDurationAvailableNotification) name:MPMovieDurationAvailableNotification object:nil];
  175. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPayerControlViewHideNotification) name:kZXPlayerControlViewHideNotification object:nil];
  176. }
  177. /// 播放状态改变, 可配合playbakcState属性获取具体状态
  178. - (void)onMPMoviePlayerPlaybackStateDidChangeNotification
  179. {
  180. NSLog(@"MPMoviePlayer PlaybackStateDidChange Notification");
  181. if (self.playbackState == MPMoviePlaybackStatePlaying) {
  182. self.videoControl.pauseButton.hidden = NO;
  183. self.videoControl.playButton.hidden = YES;
  184. [self startDurationTimer];
  185. [self.videoControl.indicatorView stopAnimating];
  186. [self.videoControl autoFadeOutControlBar];
  187. } else {
  188. self.videoControl.pauseButton.hidden = YES;
  189. self.videoControl.playButton.hidden = NO;
  190. [self stopDurationTimer];
  191. if (self.playbackState == MPMoviePlaybackStateStopped) {
  192. [self.videoControl animateShow];
  193. }
  194. }
  195. }
  196. /// 媒体网络加载状态改变
  197. - (void)onMPMoviePlayerLoadStateDidChangeNotification
  198. {
  199. NSLog(@"MPMoviePlayer LoadStateDidChange Notification");
  200. if (self.loadState & MPMovieLoadStateStalled) {
  201. [self.videoControl.indicatorView startAnimating];
  202. }
  203. }
  204. /// 视频显示状态改变
  205. - (void)onMPMoviePlayerReadyForDisplayDidChangeNotification
  206. {
  207. NSLog(@"MPMoviePlayer ReadyForDisplayDidChange Notification");
  208. }
  209. /// 确定了媒体播放时长
  210. - (void)onMPMovieDurationAvailableNotification
  211. {
  212. NSLog(@"MPMovie DurationAvailable Notification");
  213. [self startDurationTimer];
  214. [self setProgressSliderMaxMinValues];
  215. self.videoControl.fullScreenButton.hidden = NO;
  216. self.videoControl.shrinkScreenButton.hidden = YES;
  217. }
  218. /// 控制视图隐藏
  219. - (void)onPayerControlViewHideNotification
  220. {
  221. if (self.isFullscreenMode) {
  222. [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
  223. } else {
  224. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
  225. }
  226. }
  227. /// MARK: pan手势处理
  228. /// pan手势触发
  229. - (void)panDirection:(UIPanGestureRecognizer *)pan
  230. {
  231. CGPoint locationPoint = [pan locationInView:self.videoControl];
  232. CGPoint veloctyPoint = [pan velocityInView:self.videoControl];
  233. switch (pan.state) {
  234. case UIGestureRecognizerStateBegan: { // 开始移动
  235. CGFloat x = fabs(veloctyPoint.x);
  236. CGFloat y = fabs(veloctyPoint.y);
  237. if (x > y) { // 水平移动
  238. self.panDirection = ZXPanDirectionHorizontal;
  239. self.sumTime = self.currentPlaybackTime; // sumTime初值
  240. [self pause];
  241. [self stopDurationTimer];
  242. } else if (x < y) { // 垂直移动
  243. self.panDirection = ZXPanDirectionVertical;
  244. if (locationPoint.x > self.view.bounds.size.width / 2) { // 音量调节
  245. self.isVolumeAdjust = YES;
  246. } else { // 亮度调节
  247. self.isVolumeAdjust = NO;
  248. }
  249. }
  250. }
  251. break;
  252. case UIGestureRecognizerStateChanged: { // 正在移动
  253. switch (self.panDirection) {
  254. case ZXPanDirectionHorizontal: {
  255. [self horizontalMoved:veloctyPoint.x];
  256. }
  257. break;
  258. case ZXPanDirectionVertical: {
  259. [self verticalMoved:veloctyPoint.y];
  260. }
  261. break;
  262. default:
  263. break;
  264. }
  265. }
  266. break;
  267. case UIGestureRecognizerStateEnded: { // 移动停止
  268. switch (self.panDirection) {
  269. case ZXPanDirectionHorizontal: {
  270. [self setCurrentPlaybackTime:floor(self.sumTime)];
  271. [self play];
  272. [self startDurationTimer];
  273. [self.videoControl autoFadeOutControlBar];
  274. }
  275. break;
  276. case ZXPanDirectionVertical: {
  277. break;
  278. }
  279. break;
  280. default:
  281. break;
  282. }
  283. }
  284. break;
  285. default:
  286. break;
  287. }
  288. }
  289. /// pan水平移动
  290. - (void)horizontalMoved:(CGFloat)value
  291. {
  292. // 每次滑动叠加时间
  293. self.sumTime += value / 200;
  294. // 容错处理
  295. if (self.sumTime > self.duration) {
  296. self.sumTime = self.duration;
  297. } else if (self.sumTime < 0) {
  298. self.sumTime = 0;
  299. }
  300. // 时间更新
  301. double currentTime = self.sumTime;
  302. double totalTime = self.duration;
  303. [self setTimeLabelValues:currentTime totalTime:totalTime];
  304. // 提示视图
  305. self.videoControl.timeIndicatorView.labelText = self.videoControl.timeLabel.text;
  306. // 播放进度更新
  307. self.videoControl.progressSlider.value = self.sumTime;
  308. // 快进or后退 状态调整
  309. ZXTimeIndicatorPlayState playState = ZXTimeIndicatorPlayStateRewind;
  310. if (value < 0) { // left
  311. playState = ZXTimeIndicatorPlayStateRewind;
  312. } else if (value > 0) { // right
  313. playState = ZXTimeIndicatorPlayStateFastForward;
  314. }
  315. if (self.videoControl.timeIndicatorView.playState != playState) {
  316. if (value < 0) { // left
  317. NSLog(@"------fast rewind");
  318. self.videoControl.timeIndicatorView.playState = ZXTimeIndicatorPlayStateRewind;
  319. [self.videoControl.timeIndicatorView setNeedsLayout];
  320. } else if (value > 0) { // right
  321. NSLog(@"------fast forward");
  322. self.videoControl.timeIndicatorView.playState = ZXTimeIndicatorPlayStateFastForward;
  323. [self.videoControl.timeIndicatorView setNeedsLayout];
  324. }
  325. }
  326. }
  327. /// pan垂直移动
  328. - (void)verticalMoved:(CGFloat)value
  329. {
  330. if (self.isVolumeAdjust) {
  331. // 调节系统音量
  332. // [MPMusicPlayerController applicationMusicPlayer].volume 这种简单的方式调节音量也可以,只是CPU高一点点
  333. self.volumeViewSlider.value -= value / 10000;
  334. }else {
  335. // 亮度
  336. [UIScreen mainScreen].brightness -= value / 10000;
  337. }
  338. }
  339. /// MARK: 系统音量控件
  340. /// 获取系统音量控件
  341. - (void)configVolume
  342. {
  343. MPVolumeView *volumeView = [[MPVolumeView alloc] init];
  344. volumeView.center = CGPointMake(-1000, 0);
  345. [self.view addSubview:volumeView];
  346. _volumeViewSlider = nil;
  347. for (UIView *view in [volumeView subviews]){
  348. if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
  349. _volumeViewSlider = (UISlider *)view;
  350. break;
  351. }
  352. }
  353. // 使用这个category的应用不会随着手机静音键打开而静音,可在手机静音下播放声音
  354. NSError *error = nil;
  355. BOOL success = [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &error];
  356. if (!success) {/* error */}
  357. // 监听耳机插入和拔掉通知
  358. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:nil];
  359. }
  360. /// 耳机插入、拔出事件
  361. - (void)audioRouteChangeListenerCallback:(NSNotification*)notification
  362. {
  363. NSInteger routeChangeReason = [[notification.userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  364. switch (routeChangeReason) {
  365. case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
  366. NSLog(@"---耳机插入");
  367. break;
  368. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: {
  369. NSLog(@"---耳机拔出");
  370. // 拔掉耳机继续播放
  371. [self play];
  372. }
  373. break;
  374. case AVAudioSessionRouteChangeReasonCategoryChange:
  375. // called at start - also when other audio wants to play
  376. NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
  377. break;
  378. default:
  379. break;
  380. }
  381. }
  382. /// MARK: 设备方向
  383. /// 设置监听设备旋转通知
  384. - (void)configDeviceOrientationObserver
  385. {
  386. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  387. [[NSNotificationCenter defaultCenter] addObserver:self
  388. selector:@selector(onDeviceOrientationDidChange)
  389. name:UIDeviceOrientationDidChangeNotification
  390. object:nil];
  391. }
  392. /// 设备旋转方向改变
  393. - (void)onDeviceOrientationDidChange
  394. {
  395. UIDeviceOrientation orientation = self.getDeviceOrientation;
  396. if (!self.isLocked)
  397. {
  398. switch (orientation) {
  399. case UIDeviceOrientationPortrait: { // Device oriented vertically, home button on the bottom
  400. NSLog(@"home键在 下");
  401. [self restoreOriginalScreen];
  402. }
  403. break;
  404. case UIDeviceOrientationPortraitUpsideDown: { // Device oriented vertically, home button on the top
  405. NSLog(@"home键在 上");
  406. }
  407. break;
  408. case UIDeviceOrientationLandscapeLeft: { // Device oriented horizontally, home button on the right
  409. NSLog(@"home键在 右");
  410. [self changeToFullScreenForOrientation:UIDeviceOrientationLandscapeLeft];
  411. }
  412. break;
  413. case UIDeviceOrientationLandscapeRight: { // Device oriented horizontally, home button on the left
  414. NSLog(@"home键在 左");
  415. [self changeToFullScreenForOrientation:UIDeviceOrientationLandscapeRight];
  416. }
  417. break;
  418. default:
  419. break;
  420. }
  421. }
  422. }
  423. /// 切换到全屏模式
  424. - (void)changeToFullScreenForOrientation:(UIDeviceOrientation)orientation
  425. {
  426. if (self.isFullscreenMode) {
  427. return;
  428. }
  429. if (self.videoControl.isBarShowing) {
  430. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
  431. } else {
  432. [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
  433. }
  434. if (self.videoPlayerWillChangeToFullScreenModeBlock) {
  435. self.videoPlayerWillChangeToFullScreenModeBlock();
  436. }
  437. self.frame = [UIScreen mainScreen].bounds;
  438. self.isFullscreenMode = YES;
  439. self.videoControl.fullScreenButton.hidden = YES;
  440. self.videoControl.shrinkScreenButton.hidden = NO;
  441. }
  442. /// 切换到竖屏模式
  443. - (void)restoreOriginalScreen
  444. {
  445. if (!self.isFullscreenMode) {
  446. return;
  447. }
  448. if ([UIApplication sharedApplication].statusBarHidden) {
  449. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
  450. }
  451. if (self.videoPlayerWillChangeToOriginalScreenModeBlock) {
  452. self.videoPlayerWillChangeToOriginalScreenModeBlock();
  453. }
  454. self.frame = CGRectMake(0, 0, kZXVideoPlayerOriginalWidth, kZXVideoPlayerOriginalHeight);
  455. self.isFullscreenMode = NO;
  456. self.videoControl.fullScreenButton.hidden = NO;
  457. self.videoControl.shrinkScreenButton.hidden = YES;
  458. }
  459. /// 手动切换设备方向
  460. - (void)changeToOrientation:(UIDeviceOrientation)orientation
  461. {
  462. if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
  463. SEL selector = NSSelectorFromString(@"setOrientation:");
  464. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
  465. [invocation setSelector:selector];
  466. [invocation setTarget:[UIDevice currentDevice]];
  467. int val = orientation;
  468. [invocation setArgument:&val atIndex:2];
  469. [invocation invoke];
  470. }
  471. }
  472. #pragma mark -
  473. #pragma mark - Action Code
  474. /// 返回按钮点击
  475. - (void)backButtonClick
  476. {
  477. if (!self.isFullscreenMode) { // 如果是竖屏模式,返回关闭
  478. if (self) {
  479. [self.durationTimer invalidate];
  480. [self stop];
  481. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
  482. if (self.videoPlayerGoBackBlock) {
  483. [self.videoControl cancelAutoFadeOutControlBar];
  484. self.videoPlayerGoBackBlock();
  485. }
  486. }
  487. } else { // 全屏模式,返回到竖屏模式
  488. if (self.isLocked) { // 解锁
  489. [self lockButtonClick:self.videoControl.lockButton];
  490. }
  491. [self changeToOrientation:UIDeviceOrientationPortrait];
  492. }
  493. }
  494. /// 播放按钮点击
  495. - (void)playButtonClick
  496. {
  497. [self play];
  498. self.videoControl.playButton.hidden = YES;
  499. self.videoControl.pauseButton.hidden = NO;
  500. }
  501. /// 暂停按钮点击
  502. - (void)pauseButtonClick
  503. {
  504. [self pause];
  505. self.videoControl.playButton.hidden = NO;
  506. self.videoControl.pauseButton.hidden = YES;
  507. }
  508. /// 锁屏按钮点击
  509. - (void)lockButtonClick:(UIButton *)lockBtn
  510. {
  511. lockBtn.selected = !lockBtn.selected;
  512. if (lockBtn.selected) { // 锁定
  513. self.isLocked = YES;
  514. [[NSUserDefaults standardUserDefaults] setObject:@1 forKey:@"ZXVideoPlayer_DidLockScreen"];
  515. } else { // 解除锁定
  516. self.isLocked = NO;
  517. [[NSUserDefaults standardUserDefaults] setObject:@0 forKey:@"ZXVideoPlayer_DidLockScreen"];
  518. }
  519. }
  520. /// 全屏按钮点击
  521. - (void)fullScreenButtonClick
  522. {
  523. if (self.isFullscreenMode) {
  524. return;
  525. }
  526. if (self.isLocked) { // 解锁
  527. [self lockButtonClick:self.videoControl.lockButton];
  528. }
  529. // FIXME: ?
  530. [self changeToOrientation:UIDeviceOrientationLandscapeLeft];
  531. }
  532. /// 返回竖屏按钮点击
  533. - (void)shrinkScreenButtonClick
  534. {
  535. if (!self.isFullscreenMode) {
  536. return;
  537. }
  538. if (self.isLocked) { // 解锁
  539. [self lockButtonClick:self.videoControl.lockButton];
  540. }
  541. [self changeToOrientation:UIDeviceOrientationPortrait];
  542. }
  543. /// slider 按下事件
  544. - (void)progressSliderTouchBegan:(UISlider *)slider
  545. {
  546. [self pause];
  547. [self stopDurationTimer];
  548. [self.videoControl cancelAutoFadeOutControlBar];
  549. }
  550. /// slider 松开事件
  551. - (void)progressSliderTouchEnded:(UISlider *)slider
  552. {
  553. [self setCurrentPlaybackTime:floor(slider.value)];
  554. [self play];
  555. [self startDurationTimer];
  556. [self.videoControl autoFadeOutControlBar];
  557. }
  558. /// slider value changed
  559. - (void)progressSliderValueChanged:(UISlider *)slider
  560. {
  561. double currentTime = floor(slider.value);
  562. double totalTime = floor(self.duration);
  563. [self setTimeLabelValues:currentTime totalTime:totalTime];
  564. }
  565. #pragma mark -
  566. #pragma mark - getters and setters
  567. - (void)setContentURL:(NSURL *)contentURL
  568. {
  569. [self stop];
  570. [super setContentURL:contentURL];
  571. [self pause];
  572. }
  573. - (ZXVideoPlayerControlView *)videoControl
  574. {
  575. if (!_videoControl) {
  576. _videoControl = [[ZXVideoPlayerControlView alloc] init];
  577. }
  578. return _videoControl;
  579. }
  580. - (void)setFrame:(CGRect)frame
  581. {
  582. [self.view setFrame:frame];
  583. [self.videoControl setFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
  584. [self.videoControl setNeedsLayout];
  585. [self.videoControl layoutIfNeeded];
  586. }
  587. - (UIDeviceOrientation)getDeviceOrientation
  588. {
  589. return [UIDevice currentDevice].orientation;
  590. }
  591. - (void)setVideo:(ZXVideo *)video
  592. {
  593. _video = video;
  594. // 标题
  595. self.videoControl.titleLabel.text = self.video.title;
  596. // play url
  597. self.contentURL = [NSURL URLWithString:self.video.playUrl];
  598. }
  599. @end