ZLPlayer.m
2.17 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
//
// ZLPlayer.m
// CustomCamera
//
// Created by long on 2017/11/9.
// Copyright © 2017年 long. All rights reserved.
//
#import "ZLPlayer.h"
#import <AVFoundation/AVFoundation.h>
@interface ZLPlayer ()
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) AVPlayer *player;
@end
@implementation ZLPlayer
- (void)dealloc
{
[self removeObserver];
[_player pause];
_player = nil;
// NSLog(@"---- %s", __FUNCTION__);
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupUI];
}
return self;
}
- (void)setupUI
{
self.backgroundColor = [UIColor blackColor];
self.alpha = 0;
self.playerLayer = [[AVPlayerLayer alloc] init];
self.playerLayer.frame = self.bounds;
[self.layer addSublayer:self.playerLayer];
}
- (void)setVideoUrl:(NSURL *)videoUrl
{
_player = [AVPlayer playerWithURL:videoUrl];
_player.automaticallyWaitsToMinimizeStalling = NO;
[_player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
self.playerLayer.player = _player;
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"status"]) {
if (_player.status == AVPlayerStatusReadyToPlay) {
[UIView animateWithDuration:0.25 animations:^{
self.alpha = 1;
}];
}
}
}
- (void)playFinished
{
[_player seekToTime:kCMTimeZero];
[_player play];
}
- (void)play
{
[_player play];
}
- (void)pause
{
[_player pause];
}
- (void)reset
{
[self removeObserver];
[_player pause];
_player = nil;
}
- (BOOL)isPlay
{
return _player && _player.rate > 0;
}
- (void)removeObserver
{
[_player removeObserver:self forKeyPath:@"status"];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end