猎豆优选

ZLPlayer.m 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. //
  2. // ZLPlayer.m
  3. // CustomCamera
  4. //
  5. // Created by long on 2017/11/9.
  6. // Copyright © 2017年 long. All rights reserved.
  7. //
  8. #import "ZLPlayer.h"
  9. #import <AVFoundation/AVFoundation.h>
  10. @interface ZLPlayer ()
  11. @property (nonatomic, strong) AVPlayerLayer *playerLayer;
  12. @property (nonatomic, strong) AVPlayer *player;
  13. @end
  14. @implementation ZLPlayer
  15. - (void)dealloc
  16. {
  17. [self removeObserver];
  18. [_player pause];
  19. _player = nil;
  20. // NSLog(@"---- %s", __FUNCTION__);
  21. }
  22. - (instancetype)initWithFrame:(CGRect)frame
  23. {
  24. self = [super initWithFrame:frame];
  25. if (self) {
  26. [self setupUI];
  27. }
  28. return self;
  29. }
  30. - (void)setupUI
  31. {
  32. self.backgroundColor = [UIColor blackColor];
  33. self.alpha = 0;
  34. self.playerLayer = [[AVPlayerLayer alloc] init];
  35. self.playerLayer.frame = self.bounds;
  36. [self.layer addSublayer:self.playerLayer];
  37. }
  38. - (void)setVideoUrl:(NSURL *)videoUrl
  39. {
  40. _player = [AVPlayer playerWithURL:videoUrl];
  41. if (@available(iOS 10.0, *)) {
  42. _player.automaticallyWaitsToMinimizeStalling = NO;
  43. }
  44. [_player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
  45. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
  46. self.playerLayer.player = _player;
  47. self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
  48. }
  49. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
  50. {
  51. if ([keyPath isEqualToString:@"status"]) {
  52. if (_player.status == AVPlayerStatusReadyToPlay) {
  53. [UIView animateWithDuration:0.25 animations:^{
  54. self.alpha = 1;
  55. }];
  56. }
  57. }
  58. }
  59. - (void)playFinished
  60. {
  61. [_player seekToTime:kCMTimeZero];
  62. [_player play];
  63. }
  64. - (void)play
  65. {
  66. [_player play];
  67. }
  68. - (void)pause
  69. {
  70. [_player pause];
  71. }
  72. - (void)reset
  73. {
  74. [self removeObserver];
  75. [_player pause];
  76. _player = nil;
  77. }
  78. - (BOOL)isPlay
  79. {
  80. return _player && _player.rate > 0;
  81. }
  82. - (void)removeObserver
  83. {
  84. [_player removeObserver:self forKeyPath:@"status"];
  85. [[NSNotificationCenter defaultCenter] removeObserver:self];
  86. }
  87. @end