Skip to content

Instantly share code, notes, and snippets.

@leilee
Created September 25, 2017 08:20
Show Gist options
  • Save leilee/074ad2b54c3c6c9d2ecd1af9c9424a5f to your computer and use it in GitHub Desktop.
Save leilee/074ad2b54c3c6c9d2ecd1af9c9424a5f to your computer and use it in GitHub Desktop.
VideoPlayerView
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
@interface OUPVideoPlayerView : UIView
@property (nonatomic) BOOL showsPlayhead;
- (void)playItem:(AVPlayerItem*)item repeated:(BOOL)repeated;
- (void)replay;
- (void)pause;
@end
#import "OUPVideoPlayerView.h"
// TODO: playhead
@interface OUPVideoPlayerView ()
@property (nonatomic) AVPlayer* player;
@property (nonatomic) BOOL repeated;
@end
@implementation OUPVideoPlayerView
+ (Class)layerClass
{
return [AVPlayerLayer class];
}
- (AVPlayerLayer*)playerLayer
{
return (AVPlayerLayer*)self.layer;
}
#pragma mark - init
- (instancetype)initWithCoder:(NSCoder*)coder
{
self = [super initWithCoder:coder];
if (self)
{
[self commonInit];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[self commonInit];
}
return self;
}
- (void)commonInit
{
_player = [[AVPlayer alloc] init];
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
self.playerLayer.player = _player;
__weak __typeof(self) ws = self;
auto note = [NSNotificationCenter defaultCenter];
[note addObserverForName:UIApplicationWillResignActiveNotification
object:nil
queue:NSOperationQueue.mainQueue
usingBlock:^(NSNotification* note) {
[ws pause];
}];
[note addObserverForName:UIApplicationDidBecomeActiveNotification
object:nil
queue:NSOperationQueue.mainQueue
usingBlock:^(NSNotification* note) {
[ws play];
}];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - play
- (void)playItem:(AVPlayerItem*)item repeated:(BOOL)repeated
{
if (!item)
{
return;
}
_repeated = repeated;
[item seekToTime:kCMTimeZero];
[_player replaceCurrentItemWithPlayerItem:item];
[_player play];
__weak __typeof(self) ws = self;
auto note = [NSNotificationCenter defaultCenter];
[note removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
[note addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
object:nil
queue:NSOperationQueue.mainQueue
usingBlock:^(NSNotification* note) {
[ws replayIfNeeded];
}];
}
- (void)pause
{
[_player pause];
}
- (void)play
{
[_player play];
}
- (void)replay
{
[_player seekToTime:kCMTimeZero];
[_player play];
}
- (void)replayIfNeeded
{
if (_repeated)
{
[self replay];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment