HXPreviewVideoView.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. //
  2. // HXPreviewVideoView.m
  3. // HXPhotoPickerExample
  4. //
  5. // Created by Silence on 2019/11/15.
  6. // Copyright © 2019 Silence. All rights reserved.
  7. //
  8. #import "HXPreviewVideoView.h"
  9. #import <AVKit/AVKit.h>
  10. #import "HXPhotoModel.h"
  11. #import "HXPhotoDefine.h"
  12. #import "UIView+HXExtension.h"
  13. #import "UIImage+HXExtension.h"
  14. #import "NSString+HXExtension.h"
  15. #import "HXPhotoTools.h"
  16. #import "UIButton+HXExtension.h"
  17. #import "HXPhotoBottomSelectView.h"
  18. @interface HXPreviewVideoView ()
  19. @property (strong, nonatomic) AVPlayer *player;
  20. @property (strong, nonatomic) AVPlayerLayer *playerLayer;
  21. @property (assign, nonatomic) PHImageRequestID requestID;
  22. @property (strong ,nonatomic) id playbackTimeObserver;
  23. @property (assign, nonatomic) BOOL canRemovePlayerObservers;
  24. @property (assign, nonatomic) NSTimeInterval videoTotalDuration;
  25. @property (assign, nonatomic) NSTimeInterval videoCurrentTime;
  26. @property (assign, nonatomic) BOOL videoManualPause;
  27. @property (strong, nonatomic) HXHUD *loadingView;
  28. @property (strong, nonatomic) HXHUD *loadFailedView;
  29. @property (assign, nonatomic) BOOL videoLoadFailed;
  30. @property (strong, nonatomic) UIButton *playBtn;
  31. @property (assign, nonatomic) BOOL isDismiss;
  32. @property (strong, nonatomic) NSURLSessionDownloadTask *videoDownloadTask;
  33. @end
  34. @implementation HXPreviewVideoView
  35. - (void)awakeFromNib {
  36. [super awakeFromNib];
  37. [self setup];
  38. }
  39. - (instancetype)initWithFrame:(CGRect)frame {
  40. self = [super initWithFrame:frame];
  41. if (self) {
  42. [self setup];
  43. }
  44. return self;
  45. }
  46. - (void)setup {
  47. self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  48. self.playerLayer.player = self.player;
  49. self.videoManualPause = NO;
  50. self.layer.masksToBounds = YES;
  51. [self addSubview:self.playBtn];
  52. [self.playerLayer addObserver:self forKeyPath:@"readyForDisplay" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
  53. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:UIApplicationWillResignActiveNotification object:nil];
  54. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterPlayGround) name:UIApplicationDidBecomeActiveNotification object:nil];
  55. #if HasAFNetworking
  56. HXWeakSelf
  57. [HXPhotoCommon photoCommon].reachabilityStatusChangeBlock = ^(AFNetworkReachabilityStatus netStatus) {
  58. if (weakSelf.videoLoadFailed) {
  59. if (netStatus == AFNetworkReachabilityStatusReachableViaWiFi ||
  60. netStatus == AFNetworkReachabilityStatusReachableViaWWAN) {
  61. [weakSelf cancelPlayer];
  62. [weakSelf setModel:weakSelf.model];
  63. }
  64. }
  65. };
  66. #endif
  67. }
  68. - (void)setModel:(HXPhotoModel *)model {
  69. _model = model;
  70. if (self.player.currentItem != nil && !self.videoLoadFailed) return;
  71. self.playBtn.hidden = YES;
  72. self.canRemovePlayerObservers = NO;
  73. HXWeakSelf
  74. if (model.cameraVideoType == HXPhotoModelMediaTypeCameraVideoTypeNetWork) {
  75. NSString *videoFilePath = [HXPhotoTools getVideoURLFilePath:model.videoURL];
  76. NSURL *videoFileURL = [NSURL fileURLWithPath:videoFilePath];
  77. if ([HXPhotoTools fileExistsAtVideoURL:model.videoURL]) {
  78. [self requestAVAssetComplete:[AVAsset assetWithURL:videoFileURL]];
  79. return;
  80. }
  81. [self showLoading];
  82. if ([HXPhotoCommon photoCommon].downloadNetworkVideo) {
  83. self.videoDownloadTask = [[HXPhotoCommon photoCommon] downloadVideoWithURL:model.videoURL progress:^(float progress, long long downloadLength, long long totleLength, NSURL * _Nullable videoURL) {
  84. if (![videoURL.absoluteString isEqualToString:weakSelf.model.videoURL.absoluteString]) {
  85. return;
  86. }
  87. } downloadSuccess:^(NSURL * _Nullable filePath, NSURL * _Nullable videoURL) {
  88. if (![videoURL.absoluteString isEqualToString:weakSelf.model.videoURL.absoluteString]) {
  89. return;
  90. }
  91. [weakSelf requestAVAssetComplete:[AVAsset assetWithURL:videoFileURL]];
  92. } downloadFailure:^(NSError * _Nullable error, NSURL * _Nullable videoURL) {
  93. if (![videoURL.absoluteString isEqualToString:weakSelf.model.videoURL.absoluteString]) {
  94. return;
  95. }
  96. weakSelf.videoLoadFailed = YES;
  97. [weakSelf hideLoading];
  98. if (error.code != NSURLErrorCancelled) {
  99. [weakSelf showLoadFailedView];
  100. }
  101. }];
  102. return;
  103. }
  104. }
  105. [UIView cancelPreviousPerformRequestsWithTarget:self];
  106. [self performSelector:@selector(showLoading) withObject:nil afterDelay:0.2f];
  107. self.requestID = [self.model requestAVAssetStartRequestICloud:^(PHImageRequestID iCloudRequestId, HXPhotoModel *model) {
  108. if (weakSelf.model != model) return;
  109. weakSelf.requestID = iCloudRequestId;
  110. } progressHandler:^(double progress, HXPhotoModel *model) {
  111. if (weakSelf.model != model) return;
  112. } success:^(AVAsset *avAsset, AVAudioMix *audioMix, HXPhotoModel *model, NSDictionary *info) {
  113. if (weakSelf.model != model) return;
  114. [UIView cancelPreviousPerformRequestsWithTarget:weakSelf];
  115. [weakSelf requestAVAssetComplete:avAsset];
  116. } failed:^(NSDictionary *info, HXPhotoModel *model) {
  117. if (weakSelf.model != model) return;
  118. [UIView cancelPreviousPerformRequestsWithTarget:weakSelf];
  119. weakSelf.videoLoadFailed = YES;
  120. [weakSelf hideLoading];
  121. if (![[info objectForKey:PHImageCancelledKey] boolValue]) {
  122. [weakSelf showLoadFailedView];
  123. }
  124. }];
  125. }
  126. - (void)requestAVAssetComplete:(AVAsset *)avAsset {
  127. [[AVAudioSession sharedInstance] setActive:YES error:nil];
  128. [[AVAudioSession sharedInstance] setCategory: [HXPhotoCommon photoCommon].audioSessionCategory error: nil];
  129. self.avAsset = avAsset;
  130. AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:avAsset];
  131. [self.player replaceCurrentItemWithPlayerItem:playerItem];
  132. self.playerLayer.player = self.player;
  133. [self addPlayerObservers];
  134. if (self.downloadICloudAssetComplete) {
  135. self.downloadICloudAssetComplete();
  136. }
  137. }
  138. - (void)cancelPlayer {
  139. if (!self.stopCancel && self.videoDownloadTask) {
  140. [self.videoDownloadTask cancel];
  141. self.videoDownloadTask = nil;
  142. }
  143. if (self.requestID) {
  144. [[PHImageManager defaultManager] cancelImageRequest:self.requestID];
  145. self.requestID = -1;
  146. }
  147. if (self.player.currentItem != nil && !self.stopCancel) {
  148. self.playBtnDidPlay = NO;
  149. self.videoLoadFailed = NO;
  150. self.playBtn.hidden = NO;
  151. [self hideLoading];
  152. [self hideLoadFailedView];
  153. if (self.changePlayBtnState) {
  154. self.changePlayBtnState(NO);
  155. }
  156. self.videoManualPause = NO;
  157. [self.player pause];
  158. self.isPlayer = NO;
  159. [self.player seekToTime:kCMTimeZero];
  160. [self.player cancelPendingPrerolls];
  161. [self.player.currentItem cancelPendingSeeks];
  162. [self.player.currentItem.asset cancelLoading];
  163. [self removePlayerObservers];
  164. self.canRemovePlayerObservers = NO;
  165. [self.player replaceCurrentItemWithPlayerItem:nil];
  166. self.playerLayer.player = nil;
  167. [self setVideoCurrentTime:0 animation:NO];
  168. }
  169. self.stopCancel = NO;
  170. }
  171. - (void)pausePlayerAndShowNaviBar {
  172. [self.player.currentItem seekToTime:CMTimeMake(0, 1)];
  173. if ([HXPhotoCommon photoCommon].videoAutoPlayType == HXVideoAutoPlayTypeOnce) {
  174. self.isPlayer = NO;
  175. self.playBtn.hidden = NO;
  176. return;
  177. }
  178. [self.player play];
  179. self.isPlayer = YES;
  180. }
  181. - (void)addPlayerObservers {
  182. self.canRemovePlayerObservers = YES;
  183. // 播放状态
  184. [self.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
  185. // 监听loadedTimeRanges属性
  186. [self.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
  187. [self.player.currentItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
  188. [self.player.currentItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
  189. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pausePlayerAndShowNaviBar) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
  190. }
  191. - (void)removePlayerObservers {
  192. if (!self.canRemovePlayerObservers) {
  193. return;
  194. }
  195. if (self.playbackTimeObserver) {
  196. [self.player removeTimeObserver:self.playbackTimeObserver];
  197. self.playbackTimeObserver = nil;
  198. }
  199. [self.player.currentItem removeObserver:self forKeyPath:@"status"];
  200. [self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
  201. [self.player.currentItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
  202. [self.player.currentItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
  203. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
  204. }
  205. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
  206. if ([object isKindOfClass:[AVPlayerItem class]]) {
  207. if (object != self.player.currentItem) {
  208. return;
  209. }
  210. if ([keyPath isEqualToString:@"status"]) {
  211. switch (self.player.currentItem.status) {
  212. case AVPlayerItemStatusReadyToPlay: { // 可以播放了
  213. [self hideLoadFailedView];
  214. self.videoTotalDuration = CMTimeGetSeconds(self.player.currentItem.duration);
  215. if (self.model.videoDuration <= 0) {
  216. self.model.videoDuration = self.videoTotalDuration;
  217. }
  218. if (self.gotVideoDuration) {
  219. self.gotVideoDuration(self.videoTotalDuration);
  220. }
  221. if (!self.playbackTimeObserver) {
  222. // 播放进度
  223. HXWeakSelf
  224. self.playbackTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 10) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
  225. if (!weakSelf.player) {
  226. return;
  227. }
  228. //当前播放的时间
  229. NSTimeInterval currentTime = CMTimeGetSeconds(time);
  230. weakSelf.model.videoCurrentTime = currentTime;
  231. [weakSelf setVideoCurrentTime:currentTime animation:YES];
  232. }];
  233. }
  234. } break;
  235. case AVPlayerItemStatusFailed: { // 初始化失败
  236. self.videoLoadFailed = YES;
  237. [self hideLoading];
  238. [self showLoadFailedView];
  239. } break;
  240. default: {
  241. // 未知状态
  242. } break;
  243. }
  244. }else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
  245. NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
  246. CMTime duration = self.player.currentItem.duration;
  247. CGFloat totalDuration = CMTimeGetSeconds(duration);
  248. if (self.gotVideoBufferEmptyValue) {
  249. self.gotVideoBufferEmptyValue(timeInterval / totalDuration);
  250. }
  251. }else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) {
  252. //监听播放器在缓冲数据的状态
  253. }else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
  254. if (!self.player.currentItem.playbackLikelyToKeepUp) {
  255. // 缓冲中
  256. [self showLoading];
  257. }else {
  258. // 缓冲完成
  259. [self hideLoading];
  260. }
  261. }
  262. }
  263. if ([object isKindOfClass:[AVPlayerLayer class]] && [keyPath isEqualToString:@"readyForDisplay"]) {
  264. if (object != self.playerLayer) {
  265. return;
  266. }
  267. if (self.playerLayer.readyForDisplay) {
  268. if (self.player) {
  269. if ([HXPhotoCommon photoCommon].videoAutoPlayType == HXVideoAutoPlayTypeWiFi) {
  270. #if HasAFNetworking
  271. if ([HXPhotoCommon photoCommon].netStatus == AFNetworkReachabilityStatusReachableViaWiFi) {
  272. [self videoDidPlay];
  273. self.playBtnDidPlay = YES;
  274. }else {
  275. self.playBtn.hidden = NO;
  276. }
  277. #else
  278. if (!self.isDismiss) {
  279. self.playBtn.hidden = NO;
  280. }
  281. #endif
  282. }else if ([HXPhotoCommon photoCommon].videoAutoPlayType == HXVideoAutoPlayTypeAll ||
  283. [HXPhotoCommon photoCommon].videoAutoPlayType == HXVideoAutoPlayTypeOnce) {
  284. [self videoDidPlay];
  285. self.playBtnDidPlay = YES;
  286. }else {
  287. if (!self.isDismiss) {
  288. self.playBtn.hidden = NO;
  289. }
  290. }
  291. if (self.shouldPlayVideo) {
  292. self.shouldPlayVideo();
  293. }
  294. self.playerLayer.hidden = NO;
  295. }
  296. }
  297. }
  298. }
  299. - (void)videoDidPlay {
  300. [self.player play];
  301. self.isPlayer = YES;
  302. self.videoManualPause = YES;
  303. if (self.changePlayBtnState) {
  304. self.changePlayBtnState(YES);
  305. }
  306. }
  307. - (void)setVideoCurrentTime:(NSTimeInterval)videoCurrentTime animation:(BOOL)isAnimatin {
  308. _videoCurrentTime = videoCurrentTime;
  309. if (self.changeValue) {
  310. CGFloat value = 0;
  311. if (self.videoTotalDuration > 0) {
  312. value = videoCurrentTime / self.videoTotalDuration;
  313. }
  314. self.changeValue(value, isAnimatin);
  315. }
  316. if (self.gotVideoCurrentTime) {
  317. self.gotVideoCurrentTime(videoCurrentTime);
  318. }
  319. }
  320. - (void)appDidEnterBackground {
  321. if (!self.player.currentItem) {
  322. return;
  323. }
  324. [self.player pause];
  325. self.isPlayer = NO;
  326. }
  327. - (void)appDidEnterPlayGround {
  328. if (!self.player.currentItem) {
  329. return;
  330. }
  331. if (self.videoManualPause && self.playBtnDidPlay) {
  332. [self.player play];
  333. self.isPlayer = YES;
  334. }
  335. }
  336. - (void)setPlayBtnHidden:(BOOL)playBtnHidden {
  337. _playBtnHidden = playBtnHidden;
  338. self.playBtn.hidden = playBtnHidden;
  339. }
  340. - (void)didPlayBtnClickWithSelected:(BOOL)isSelected {
  341. self.videoManualPause = isSelected;
  342. self.playBtnDidPlay = YES;
  343. self.isPlayer = isSelected;
  344. if (isSelected) {
  345. [self.player play];
  346. }else {
  347. [self.player pause];
  348. }
  349. }
  350. - (void)changePlayerTimeWithValue:(CGFloat)value type:(HXPreviewVideoSliderType)type {
  351. if (!self.player.currentItem) {
  352. return;
  353. }
  354. CGFloat seconds = self.videoTotalDuration * value;
  355. seconds = MAX(0, seconds);
  356. seconds = MIN(seconds, self.videoTotalDuration);
  357. CMTime time = CMTimeMakeWithSeconds(seconds , self.player.currentTime.timescale);
  358. HXWeakSelf
  359. [self.player seekToTime:time toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
  360. if (finished) {
  361. [weakSelf setVideoCurrentTime:seconds animation:NO];
  362. if (type == HXPreviewVideoSliderTypeTouchUpInSide) {
  363. [weakSelf videoDidPlay];
  364. }
  365. }
  366. }];
  367. if (type == HXPreviewVideoSliderTypeTouchDown) {
  368. [self.player pause];
  369. self.isPlayer = NO;
  370. if (self.changePlayBtnState) {
  371. self.changePlayBtnState(NO);
  372. }
  373. self.videoManualPause = NO;
  374. }
  375. }
  376. - (NSTimeInterval)availableDuration {
  377. if (!self.player.currentItem) {
  378. return 0;
  379. }
  380. NSArray *loadedTimeRanges = [self.player.currentItem loadedTimeRanges];
  381. CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
  382. float startSeconds = CMTimeGetSeconds(timeRange.start);
  383. float durationSeconds = CMTimeGetSeconds(timeRange.duration);
  384. NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
  385. return result;
  386. }
  387. - (void)showOtherView {
  388. self.isDismiss = NO;
  389. self.changeSliderHidden(NO);
  390. [UIView animateWithDuration:0.2 animations:^{
  391. self.loadFailedView.alpha = 1;
  392. self.loadingView.alpha = 1;
  393. self.playBtn.alpha = 1;
  394. }];
  395. }
  396. - (void)hideOtherView:(BOOL)animatoin {
  397. self.isDismiss = YES;
  398. self.changeSliderHidden(YES);
  399. if (!animatoin) {
  400. self.loadingView.hidden = YES;
  401. self.loadFailedView.hidden = YES;
  402. self.playBtn.hidden = YES;
  403. return;
  404. }
  405. [UIView animateWithDuration:0.2 animations:^{
  406. self.loadFailedView.alpha = 0;
  407. self.loadingView.alpha = 0;
  408. self.playBtn.alpha = 0;
  409. }];
  410. }
  411. - (UIButton *)playBtn {
  412. if (!_playBtn) {
  413. _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  414. [_playBtn setImage:[UIImage hx_imageNamed:@"hx_multimedia_videocard_play"] forState:UIControlStateNormal];
  415. [_playBtn addTarget:self action:@selector(didPlayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
  416. _playBtn.hx_size = _playBtn.currentImage.size;
  417. }
  418. return _playBtn;
  419. }
  420. - (void)didPlayBtnClick:(UIButton *)button {
  421. [self videoDidPlay];
  422. self.playBtnDidPlay = YES;
  423. button.hidden = YES;
  424. if (self.playBtnDidClick) {
  425. self.playBtnDidClick(YES);
  426. }
  427. }
  428. - (void)setPlayBtnDidPlay:(BOOL)playBtnDidPlay {
  429. _playBtnDidPlay = playBtnDidPlay;
  430. if (playBtnDidPlay && !self.playBtn.hidden) {
  431. self.playBtn.hidden = YES;
  432. }
  433. }
  434. + (Class)layerClass {
  435. return AVPlayerLayer.class;
  436. }
  437. - (AVPlayerLayer *)playerLayer {
  438. return (AVPlayerLayer *)self.layer;
  439. }
  440. - (AVPlayer *)player {
  441. if (!_player) {
  442. _player = [[AVPlayer alloc] init];
  443. }
  444. return _player;
  445. }
  446. - (HXHUD *)loadingView {
  447. if (!_loadingView) {
  448. _loadingView = [[HXHUD alloc] initWithFrame:CGRectMake(0, 0, 95, 95) imageName:nil text:nil];
  449. [_loadingView showloading];
  450. }
  451. return _loadingView;
  452. }
  453. - (void)showLoading {
  454. [self addSubview:self.loadingView];
  455. }
  456. - (void)hideLoading {
  457. [self.loadingView removeFromSuperview];
  458. }
  459. - (HXHUD *)loadFailedView {
  460. if (!_loadFailedView) {
  461. NSString *text = @"视频加载失败!";
  462. CGFloat hudW = [UILabel hx_getTextWidthWithText:text height:15 fontSize:14];
  463. if (hudW > self.hx_w - 60) {
  464. hudW = self.hx_w - 60;
  465. }
  466. if (hudW < 100) {
  467. hudW = 100;
  468. }
  469. CGFloat hudH = [UILabel hx_getTextHeightWithText:text width:hudW fontSize:14];
  470. _loadFailedView = [[HXHUD alloc] initWithFrame:CGRectMake(0, 0, hudW + 20, 110 + hudH - 15) imageName:@"hx_alert_failed" text:text];
  471. }
  472. return _loadFailedView;
  473. }
  474. - (void)showLoadFailedView {
  475. [self addSubview:self.loadFailedView];
  476. }
  477. - (void)hideLoadFailedView {
  478. [self.loadFailedView removeFromSuperview];
  479. }
  480. - (void)layoutSubviews {
  481. [super layoutSubviews];
  482. self.playerLayer.frame = self.bounds;
  483. self.loadingView.hx_centerX = self.hx_w / 2;
  484. self.loadingView.hx_centerY = self.hx_h / 2;
  485. self.loadFailedView.hx_centerX = self.hx_w / 2;
  486. self.loadFailedView.hx_centerY = self.hx_h / 2;
  487. self.playBtn.hx_centerX = self.hx_w / 2;
  488. self.playBtn.hx_centerY = self.hx_h / 2;
  489. }
  490. - (void)dealloc {
  491. [self.playerLayer removeObserver:self forKeyPath:@"readyForDisplay"];
  492. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
  493. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
  494. [self removePlayerObservers];
  495. if (HXShowLog) NSSLog(@"dealloc");
  496. }
  497. @end
  498. @interface HXPreviewVideoSliderView ()
  499. @property (strong, nonatomic) HXSlider *sliderView;
  500. @property (strong, nonatomic) UIProgressView *progressView;
  501. @property (strong, nonatomic) UIButton *playBtn;
  502. @property (strong, nonatomic) UILabel *currentTimeLb;
  503. @property (strong, nonatomic) UILabel *totalTimeLb;
  504. @property (strong, nonatomic) UIVisualEffectView *effectView;
  505. @property (strong, nonatomic) UIPanGestureRecognizer *panGesture;
  506. @end
  507. @implementation HXPreviewVideoSliderView
  508. - (instancetype)initWithFrame:(CGRect)frame {
  509. self = [super initWithFrame:frame];
  510. if (self) {
  511. self.layer.masksToBounds = YES;
  512. self.layer.cornerRadius = 5.f;
  513. self.panGesture = [[UIPanGestureRecognizer alloc] init];
  514. [self addGestureRecognizer:self.panGesture];
  515. [self addSubview:self.effectView];
  516. [self addSubview:self.progressView];
  517. [self addSubview:self.sliderView];
  518. [self addSubview:self.playBtn];
  519. [self addSubview:self.currentTimeLb];
  520. [self addSubview:self.totalTimeLb];
  521. }
  522. return self;
  523. }
  524. - (void)show {
  525. if (self.hidden) {
  526. self.hidden = NO;
  527. [UIView animateWithDuration:0.25 animations:^{
  528. self.alpha = 1;
  529. }];
  530. }
  531. }
  532. - (void)hide {
  533. if (!self.hidden) {
  534. [UIView animateWithDuration:0.25 animations:^{
  535. self.alpha = 0;
  536. } completion:^(BOOL finished) {
  537. self.hidden = YES;
  538. }];
  539. }
  540. }
  541. - (void)setCurrentValue:(CGFloat)currentValue animation:(BOOL)isAnimation {
  542. _currentValue = currentValue;
  543. [self.sliderView setCurrentValue:currentValue animation:isAnimation];
  544. }
  545. - (void)setCurrentValue:(CGFloat)currentValue {
  546. _currentValue = currentValue;
  547. [self.sliderView setCurrentValue:currentValue animation:NO];
  548. }
  549. - (void)setProgressValue:(CGFloat)progressValue {
  550. _progressValue = progressValue;
  551. self.progressView.progress = progressValue;
  552. }
  553. - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
  554. UIView *view = [super hitTest:point withEvent:event];
  555. if([view isKindOfClass:[HXSlider class]]){
  556. self.panGesture.enabled = NO;
  557. }else {
  558. self.panGesture.enabled = YES;
  559. }
  560. return view;
  561. }
  562. - (void)layoutSubviews {
  563. [super layoutSubviews];
  564. self.playBtn.hx_x = 5;
  565. self.playBtn.hx_size = CGSizeMake(30, 30.f);
  566. self.playBtn.hx_centerY = self.hx_h / 2.f;
  567. self.currentTimeLb.hx_size = CGSizeMake(60, 30.f);
  568. self.currentTimeLb.hx_x = CGRectGetMaxX(self.playBtn.frame);
  569. self.currentTimeLb.hx_centerY = self.hx_h / 2.f;
  570. self.totalTimeLb.hx_size = CGSizeMake(60, 30.f);
  571. self.totalTimeLb.hx_x = self.hx_w - self.totalTimeLb.hx_w - 10;
  572. self.totalTimeLb.hx_centerY = self.hx_h / 2.f;
  573. CGFloat progressX = CGRectGetMaxX(self.currentTimeLb.frame) + 5;
  574. CGFloat progressW = self.hx_w - progressX - 10 - (self.hx_w - self.totalTimeLb.hx_x);
  575. self.progressView.frame = CGRectMake(progressX, 0, progressW, 2);
  576. self.progressView.hx_centerY = self.hx_h / 2.f;
  577. self.sliderView.frame = CGRectMake(progressX, 0, progressW, 30);
  578. self.sliderView.hx_centerY = self.hx_h / 2.f;
  579. self.effectView.frame = self.bounds;
  580. }
  581. - (HXSlider *)sliderView {
  582. if (!_sliderView) {
  583. _sliderView = [[HXSlider alloc] init];
  584. HXWeakSelf
  585. _sliderView.sliderChanged = ^(CGFloat value) {
  586. if (weakSelf.sliderChangedValueBlock) {
  587. weakSelf.sliderChangedValueBlock(value, HXPreviewVideoSliderTypeChanged);
  588. }
  589. };
  590. _sliderView.sliderTouchDown = ^(CGFloat value) {
  591. if (weakSelf.sliderChangedValueBlock) {
  592. weakSelf.sliderChangedValueBlock(value, HXPreviewVideoSliderTypeTouchDown);
  593. }
  594. };
  595. _sliderView.sliderTouchUpInSide = ^(CGFloat value) {
  596. if (weakSelf.sliderChangedValueBlock) {
  597. weakSelf.sliderChangedValueBlock(value, HXPreviewVideoSliderTypeTouchUpInSide);
  598. }
  599. };
  600. }
  601. return _sliderView;
  602. }
  603. - (UIProgressView *)progressView {
  604. if (!_progressView) {
  605. _progressView = [[UIProgressView alloc] init];
  606. _progressView.trackTintColor = [[UIColor whiteColor] colorWithAlphaComponent:0.3f];
  607. _progressView.progressTintColor = [[UIColor whiteColor] colorWithAlphaComponent:0.6f];
  608. }
  609. return _progressView;
  610. }
  611. - (UIButton *)playBtn {
  612. if (!_playBtn) {
  613. _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  614. [_playBtn setImage:[UIImage hx_imageNamed:@"hx_video_play"] forState:UIControlStateNormal];
  615. [_playBtn setImage:[UIImage hx_imageNamed:@"hx_video_ pause"] forState:UIControlStateSelected];
  616. [_playBtn addTarget:self action:@selector(didPlayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
  617. [_playBtn hx_setEnlargeEdgeWithTop:20 right:20 bottom:20 left:20];
  618. }
  619. return _playBtn;
  620. }
  621. - (void)didPlayBtnClick:(UIButton *)button {
  622. button.selected = !button.isSelected;
  623. if (self.didPlayBtnBlock) {
  624. self.didPlayBtnBlock(button.selected);
  625. }
  626. }
  627. - (void)setPlayBtnSelected:(BOOL)playBtnSelected {
  628. self.playBtn.selected = playBtnSelected;
  629. }
  630. - (BOOL)playBtnSelected {
  631. return self.playBtn.selected;
  632. }
  633. - (UILabel *)currentTimeLb {
  634. if (!_currentTimeLb) {
  635. _currentTimeLb = [[UILabel alloc] init];
  636. _currentTimeLb.text = @"00:00";
  637. _currentTimeLb.textColor = [UIColor whiteColor];
  638. _currentTimeLb.font = [UIFont systemFontOfSize:13];
  639. _currentTimeLb.textAlignment = NSTextAlignmentCenter;
  640. }
  641. return _currentTimeLb;
  642. }
  643. - (void)setCurrentTime:(NSString *)currentTime {
  644. _currentTime = currentTime;
  645. self.currentTimeLb.text = currentTime;
  646. }
  647. - (UILabel *)totalTimeLb {
  648. if (!_totalTimeLb) {
  649. _totalTimeLb = [[UILabel alloc] init];
  650. _totalTimeLb.text = @"--:--";
  651. _totalTimeLb.textColor = [UIColor whiteColor];
  652. _totalTimeLb.font = [UIFont systemFontOfSize:13];
  653. _totalTimeLb.textAlignment = NSTextAlignmentCenter;
  654. }
  655. return _totalTimeLb;
  656. }
  657. - (void)setTotalTime:(NSString *)totalTime {
  658. _totalTime = totalTime;
  659. self.totalTimeLb.text = totalTime;
  660. }
  661. - (UIVisualEffectView *)effectView {
  662. if (!_effectView) {
  663. UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
  664. _effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
  665. }
  666. return _effectView;
  667. }
  668. @end
  669. @interface HXSlider ()<UIGestureRecognizerDelegate>
  670. @property (strong, nonatomic) UIImageView *thumbView;
  671. @property (strong, nonatomic) UIView *lineView;
  672. @property (assign, nonatomic) CGRect thumbViewFrame;
  673. @property (strong, nonatomic) HXPanGestureRecognizer *panGesture;
  674. @end
  675. @implementation HXSlider
  676. - (instancetype)initWithFrame:(CGRect)frame {
  677. self = [super initWithFrame:frame];
  678. if (self) {
  679. self.currentValue = 0;
  680. [self addSubview:self.lineView];
  681. [self addSubview:self.thumbView];
  682. self.panGesture = [[HXPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizerClick:)];
  683. self.panGesture.delegate = self;
  684. [self addGestureRecognizer:self.panGesture];
  685. }
  686. return self;
  687. }
  688. - (void)panGestureRecognizerClick:(HXPanGestureRecognizer *)gestRecog {
  689. switch (gestRecog.state) {
  690. case UIGestureRecognizerStateBegan: {
  691. CGPoint point = [gestRecog locationInView:self];
  692. if (point.x < self.thumbView.hx_x - 20 ||
  693. point.x > CGRectGetMaxX(self.thumbView.frame) + 20) {
  694. gestRecog.enabled = NO;
  695. gestRecog.enabled = YES;
  696. return;
  697. }
  698. if (point.y < self.thumbView.hx_y - 20 ||
  699. point.y > CGRectGetMaxY(self.thumbView.frame) + 20) {
  700. gestRecog.enabled = NO;
  701. gestRecog.enabled = YES;
  702. return;
  703. }
  704. if (self.sliderTouchDown) {
  705. self.sliderTouchDown(self.currentValue);
  706. }
  707. if (CGRectEqualToRect(self.thumbViewFrame, CGRectZero)) {
  708. self.thumbViewFrame = self.thumbView.frame;
  709. }
  710. } break;
  711. case UIGestureRecognizerStateChanged: {
  712. CGPoint specifiedPoint = [gestRecog translationInView:self];
  713. CGRect rect = self.thumbViewFrame;
  714. rect.origin.x += specifiedPoint.x;
  715. if (rect.origin.x < 0) {
  716. rect.origin.x = 0;
  717. }
  718. if (rect.origin.x > self.hx_w - self.thumbView.hx_w) {
  719. rect.origin.x = self.hx_w - self.thumbView.hx_w;
  720. }
  721. self.thumbView.frame = rect;
  722. CGFloat lineW = CGRectGetMaxX(self.thumbView.frame);
  723. if (lineW < 0) {
  724. lineW = 0;
  725. }
  726. if (lineW > self.hx_w) {
  727. lineW = self.hx_w;
  728. }
  729. self.lineView.hx_w = lineW;
  730. _currentValue = self.thumbView.hx_x / (self.hx_w - self.thumbView.hx_w);
  731. if (self.sliderChanged) {
  732. self.sliderChanged(self.currentValue);
  733. }
  734. } break;
  735. case UIGestureRecognizerStateEnded:
  736. case UIGestureRecognizerStateCancelled:
  737. case UIGestureRecognizerStateFailed: {
  738. if (self.sliderTouchUpInSide) {
  739. self.sliderTouchUpInSide(self.currentValue);
  740. }
  741. self.thumbViewFrame = CGRectZero;
  742. } break;
  743. default:
  744. break;
  745. }
  746. }
  747. - (void)setCurrentValue:(CGFloat)currentValue animation:(BOOL)isAnimation {
  748. if (_currentValue == 1 && currentValue == 0) {
  749. isAnimation = NO;
  750. }
  751. if (self.panGesture.state == UIGestureRecognizerStateChanged ||
  752. self.panGesture.state == UIGestureRecognizerStateBegan ||
  753. self.panGesture.state == UIGestureRecognizerStateEnded) {
  754. return;
  755. }
  756. if (currentValue < 0) {
  757. currentValue = 0;
  758. }
  759. if (currentValue > 1) {
  760. currentValue = 1;
  761. }
  762. if (isAnimation) {
  763. [UIView animateWithDuration:0.1f delay:0 options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionCurveLinear | UIViewAnimationOptionOverrideInheritedDuration | UIViewAnimationOptionOverrideInheritedCurve animations:^{
  764. self.currentValue = currentValue;
  765. } completion:nil];
  766. }else {
  767. self.currentValue = currentValue;
  768. }
  769. }
  770. - (void)setCurrentValue:(CGFloat)currentValue {
  771. _currentValue = currentValue;
  772. if (currentValue < 0) {
  773. currentValue = 0;
  774. }
  775. if (currentValue > 1) {
  776. currentValue = 1;
  777. }
  778. CGFloat thumbX = (self.hx_w - self.thumbView.hx_w) * currentValue;
  779. if (thumbX > self.hx_w - self.thumbView.hx_w) {
  780. thumbX = self.hx_w - self.thumbView.hx_w;
  781. }
  782. if (thumbX < 0) {
  783. thumbX = 0;
  784. }
  785. self.lineView.hx_w = thumbX + self.thumbView.hx_w;
  786. self.thumbView.hx_x = thumbX;
  787. }
  788. - (void)layoutSubviews {
  789. [super layoutSubviews];
  790. self.lineView.hx_centerY = self.hx_h / 2.f;
  791. self.thumbView.hx_centerY = self.hx_h / 2.f;
  792. }
  793. - (UIView *)lineView {
  794. if (!_lineView) {
  795. _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.thumbView.hx_size.width, 2)];
  796. _lineView.backgroundColor = [UIColor whiteColor];
  797. }
  798. return _lineView;
  799. }
  800. - (UIImageView *)thumbView {
  801. if (!_thumbView) {
  802. _thumbView = [[UIImageView alloc] initWithImage:[UIImage hx_imageNamed:@"hx_video_progress"]];
  803. _thumbView.hx_size = _thumbView.image.size;
  804. }
  805. return _thumbView;
  806. }
  807. @end
  808. @implementation HXPanGestureRecognizer
  809. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  810. [super touchesBegan:touches withEvent:event];
  811. self.state = UIGestureRecognizerStateBegan;
  812. if ([self.delegate isKindOfClass:[HXPhotoBottomSelectView class]]) {
  813. [(HXPhotoBottomSelectView *)self.delegate panGestureReconClick:self];
  814. }
  815. }
  816. @end