|
//
// TPMovieContent.m
// ThePaperBase
//
// Created by zhousan on 16/1/5.
// Copyright © 2016年 scar1900. All rights reserved.
//
#import "TPMovieContent.h"
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>
#import "TPLightView.h"
#import <MediaPlayer/MediaPlayer.h>
#import "PlayerView.h"
#import "liveViewModel.h"
@interface TPMovieContent ()<UIGestureRecognizerDelegate> {
CGPoint beginPoint;
CGPoint movePoint;
CGPoint tempPoint;
UISlider* volumeViewSlider;
CGFloat sysV;
CGFloat value;
NSString *directionString;
CTCallCenter *callCenter;
CGRect vedioFrame;
NSString *_totalTime;
BOOL isFull;
BOOL isHours;
BOOL isShow;
UIPanGestureRecognizer *panHandler;
BOOL isLive;
UITapGestureRecognizer *tap;
BOOL isFirstIn;
CGFloat changePoint;
BOOL isCut;
BOOL isLoading;
BOOL isCancel;
NSString *videoDefinition;
}
@property (nonatomic, strong) UIView *playBackView;
@property (nonatomic, strong) UILabel *totalLabel;
@property (nonatomic, strong) UILabel *currLabel;
@property (nonatomic, strong) UILabel *barTotalLabel;
@property (nonatomic, strong) UILabel *barcurrLabel;
@property (nonatomic, strong) UIImageView *playImage;
@property (nonatomic, strong) UIProgressView *timeSlider;
@property (nonatomic, strong) TPLightView *lightView;
@property (nonatomic, strong) PlayerView *playerView;
@property (nonatomic, strong) UIView *bottonView;
@property (nonatomic, strong) UIButton *playPasuButton;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) UIButton *cutPhotoBtn;
@property (nonatomic, strong) UIButton *fullscreenButton;
@property (nonatomic, strong) UIButton *standardButton;
@property (nonatomic, strong) UIButton *highButton;
@property (nonatomic, strong) UIButton *superButton;
@property (nonatomic, strong) UISlider *durationSlider;
@property (nonatomic, strong) UIProgressView *availablePro;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) id playbackTimeObserver;
@property (nonatomic, strong) UIActivityIndicatorView *activityView;
@property (nonatomic, strong) UILabel *cancelLabel;
@property (nonatomic, strong) UIImageView *cancelImageView;
@property (nonatomic, strong) UIButton *rateButton;
@property (nonatomic, strong) UIView *rateView;
@end
@implementation TPMovieContent
# pragma mark - Construct/Destruct
- (id)initWithFrame:(CGRect)frame contentUrlDic:(NSMutableDictionary *)contentUrlDic {
if ( (self = [super init]) ) {
isHours = NO;
isShow = NO;
isLive = YES;
self.isEmbedded = NO;
isFirstIn = YES;
changePoint = 0;
isCut = NO;
isLoading = YES;
isCancel = NO;
self.contentUrlDic = [NSMutableDictionary dictionaryWithDictionary:contentUrlDic];
[self.standardButton setEnabled:YES];
if (self.contentUrlDic[@"high"])
[self.highButton setEnabled:YES];
if (self.contentUrlDic[@"super"])
[self.superButton setEnabled:YES];
videoDefinition = [TPUserDefault instance].videoDefinition;
if (([videoDefinition isEqualToString:@"high"] && isBlankString(self.contentUrlDic[@"high"])) || ([videoDefinition isEqualToString:@"super"] && isBlankString(self.contentUrlDic[@"super"])))
videoDefinition = @"standard";
self.contentURL = [NSURL URLWithString:self.contentUrlDic[videoDefinition]];
self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.contentUrlDic[videoDefinition]]];
[self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
[self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
self.playerView = [[PlayerView alloc] initWithFrame:CGRectZero];
self.playerView.player = _player;
[self.view addSubview:self.playerView];
[self.player play];
self.player.rate = 1;
vedioFrame = frame;
[self.playerView makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
panHandler = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panHandler:)];
panHandler.maximumNumberOfTouches = 1;
[panHandler delaysTouchesBegan];
[self.view addGestureRecognizer:panHandler];
tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandler:)];
[self.view addGestureRecognizer:tap];
// 添加视频播放结束通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
// self.view.frame = frame;
MPVolumeView *volumeView = [[MPVolumeView alloc] init];
volumeView.showsVolumeSlider = YES;
for (UIView *view in [volumeView subviews]){
if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
volumeViewSlider = (UISlider*)view;
break;
}
}
sysV = volumeViewSlider.value;
[UIScreen mainScreen].wantsSoftwareDimming = YES;
[volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
self.view.backgroundColor = [UIColor blackColor];
[MobClick event:@"4"];
_movieFullscreen = NO;
if (!_movieBackgroundView) {
_movieBackgroundView = [[UIView alloc] init];
_movieBackgroundView.alpha = 0.f;
[_movieBackgroundView setBackgroundColor:[UIColor blackColor]];
}
[self.view addSubview:self.playBackView];
[self.view addSubview:self.lightView];
[self.lightView makeConstraints:^(MASConstraintMaker *make) {
make.centerX.equalTo(self.view);
make.centerY.equalTo(self.view);
make.size.mas_equalTo(CGSizeMake(155, 155));
}];
[self.playBackView makeConstraints:^(MASConstraintMaker *make) {
make.centerX.equalTo(self.view);
make.centerY.equalTo(self.view);
make.size.mas_equalTo(CGSizeMake(140, 60));
}];
// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationWillChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
callCenter = [[CTCallCenter alloc] init];
__block typeof(self) weakSelf = self;
callCenter.callEventHandler = ^(CTCall* call) {
if ([call.callState isEqualToString:CTCallStateDisconnected])
{
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.player play];
weakSelf.playPasuButton.selected = NO;
});
NSLog(@"Call has been disconnected");
}
else if ([call.callState isEqualToString:CTCallStateConnected])
{
NSLog(@"Call has just been connected");
}
else if([call.callState isEqualToString:CTCallStateIncoming])
{
NSLog(@"Call is incoming");
}
else if ([call.callState isEqualToString:CTCallStateDialing])
{
NSLog(@"call is dialing");
}
else
{
NSLog(@"Nothing is done");
}
};
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomActive) name:APP_REFRESH_NOTIFICATION object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resignActive) name:APP_RESIGNACTIVE_NOTIFICATION object:nil];
[self creatSubView];
}
return self;
}
- (void)becomActive {
[self.player play];
self.playPasuButton.selected = NO;
}
- (void)resignActive {
[self.player pause];
self.playPasuButton.selected = YES;
}
- (void)creatSubView {
[self.view addSubview:self.bottonView];
[self.bottonView makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.playerView);
make.right.equalTo(self.playerView);
make.bottom.equalTo(self.playerView);
make.height.mas_equalTo(40);
}];
[self.bottonView addSubview:self.playPasuButton];
[self.playPasuButton makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.bottonView).offset(10);
make.top.equalTo(self.bottonView).offset(10);
make.size.mas_equalTo(CGSizeMake(15, 20));
}];
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = [UIColor lightGrayColor];
[self.bottonView addSubview:view];
[view makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.playPasuButton.right).offset(12);
make.centerY.equalTo(self.bottonView).offset(1);
make.right.equalTo(self.bottonView).offset(-74/2);
make.height.mas_equalTo(2);
}];
[self.bottonView addSubview:self.availablePro];
[self.availablePro makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.playPasuButton.right).offset(12);
make.centerY.equalTo(self.bottonView).offset(1);
make.right.equalTo(self.bottonView).offset(-74/2);
make.height.mas_equalTo(2);
}];
[self.bottonView addSubview:self.durationSlider];
[self.durationSlider makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.playPasuButton.right).offset(12);
make.centerY.equalTo(self.bottonView);
make.right.equalTo(self.bottonView).offset(-74/2);
make.height.mas_equalTo(40);
}];
[self.bottonView addSubview:self.fullscreenButton];
[self.fullscreenButton makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.bottonView);
make.centerY.equalTo(self.bottonView);
make.size.mas_equalTo(CGSizeMake(37/2+20, 40));
}];
[self.view addSubview:self.cutPhotoBtn];
[self.cutPhotoBtn makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.view.right).offset(-12);
make.centerY.equalTo(self.view);
make.size.mas_equalTo(CGSizeMake(25, 25));
}];
[self.view addSubview:self.rateButton];
[self.rateButton setTitle:[self changeStr:videoDefinition] forState:UIControlStateNormal];
[self.rateButton makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.view.right).offset(-12);
make.bottom.equalTo(self.cutPhotoBtn.top).offset(-12);
make.size.mas_equalTo(CGSizeMake(50, 25));
}];
self.rateView = [[UIView alloc] initWithFrame:CGRectZero];
self.rateView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
self.rateView.hidden = YES;
[self.view addSubview:self.rateView];
[self.rateView makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.view.right);
make.top.equalTo(self.rateButton);
make.size.mas_equalTo(CGSizeMake(150, 25));
}];
[self.rateView addSubview:self.superButton];
[self.superButton makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.rateView);
make.top.equalTo(self.rateView);
make.size.mas_equalTo(CGSizeMake(50, 25));
}];
[self.rateView addSubview:self.highButton];
[self.highButton makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.superButton.left);
make.top.equalTo(self.rateView);
make.size.mas_equalTo(CGSizeMake(50, 25));
}];
[self.rateView addSubview:self.standardButton];
[self.standardButton makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.highButton.left);
make.top.equalTo(self.rateView);
make.size.mas_equalTo(CGSizeMake(50, 25));
}];
[self.view addSubview:self.closeButton];
[self.closeButton makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.view);
make.top.equalTo(self.view);
make.size.mas_equalTo(CGSizeMake(41/2+24, 41/2+24));
}];
[self.bottonView addSubview:self.barTotalLabel];
[self.barTotalLabel makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(view);
make.top.equalTo(view.bottom).offset(3);
make.size.mas_equalTo(CGSizeMake(40, 10));
}];
[self.bottonView addSubview:self.barcurrLabel];
[self.barcurrLabel makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.barTotalLabel.left);
make.top.equalTo(self.barTotalLabel);
make.size.mas_equalTo(CGSizeMake(40, 10));
}];
[self.view addSubview:self.activityView];
[self.activityView makeConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(CGSizeMake(40, 40));
make.centerX.equalTo(self.view);
make.centerY.equalTo(self.view);
}];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.activityView.hidden = NO;
[self.activityView startAnimating];
});
}
- (NSString *)changeStr:(NSString *)str {
if ([str isEqualToString:@"standard"]) {
return @"标清";
}else if ([str isEqualToString:@"high"]) {
return @"高清";
}else if ([str isEqualToString:@"super"]) {
return @"超清";
}
return nil;
}
- (UIButton *)rateButton {
if (nil == _rateButton) {
_rateButton = [UIButton buttonWithType:UIButtonTypeCustom];
_rateButton.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
_rateButton.titleLabel.textAlignment = NSTextAlignmentCenter;
[_rateButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_rateButton addTarget:self action:@selector(rateButtonClick:) forControlEvents:UIControlEventTouchUpInside];
_rateButton.alpha = 0;
}
return _rateButton;
}
- (void)rateButtonClick:(UIButton *)button {
if (button.selected) {
CGRect rect = self.rateView.frame;
rect.origin.x = self.view.frame.size.width;
[UIView animateWithDuration:0.35 animations:^{
self.rateView.frame = rect;
} completion:^(BOOL finished) {
button.selected = NO;
self.rateView.hidden = YES;
}];
}else {
CGRect rect = self.rateView.frame;
self.rateView.hidden = NO;
rect.origin.x = self.view.frame.size.width - 220;
[UIView animateWithDuration:0.35 animations:^{
self.rateView.frame = rect;
} completion:^(BOOL finished) {
button.selected = YES;
}];
}
}
- (UIActivityIndicatorView *)activityView {
if (!_activityView) {
_activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
_activityView.hidesWhenStopped = YES;
_activityView.hidden = YES;
}
return _activityView;
}
- (UIView *)bottonView {
if (_bottonView == nil) {
_bottonView = [[UIView alloc] initWithFrame:CGRectZero];
_bottonView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
_bottonView.alpha = 0;
}
return _bottonView;
}
- (UIButton *)playPasuButton {
if (nil == _playPasuButton) {
_playPasuButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_playPasuButton setImage:Image(@"video/pauseBtn.png") forState:UIControlStateNormal];
[_playPasuButton setImage:Image(@"video/playBtn.png") forState:UIControlStateSelected];
[_playPasuButton setSelected:NO];
[_playPasuButton addTarget:self action:@selector(playPausePressed:) forControlEvents:UIControlEventTouchUpInside];
}
return _playPasuButton;
}
- (void)playPausePressed:(UIButton *)button {
if (button.selected) {
[self.player play];
}else {
[self.player pause];
}
button.selected = !button.selected;
}
- (UIButton *)closeButton {
if (nil == _closeButton) {
_closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_closeButton setImage:Image(@"video/closeBtn.png") forState:UIControlStateNormal];
[_closeButton addTarget:self action:@selector(closeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
_closeButton.alpha = 0;
}
return _closeButton;
}
- (void)closeButtonClick:(id)sender {
if ([self.delegate respondsToSelector:@selector(closeHandler)]) {
[self.delegate closeHandler];
}
}
- (UIButton *)fullscreenButton {
if (nil == _fullscreenButton) {
_fullscreenButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_fullscreenButton setImage:Image(@"video/inFullScreen.png") forState:UIControlStateNormal];
[_fullscreenButton setImage:Image(@"video/outFullScreen.png") forState:UIControlStateSelected];
[_fullscreenButton addTarget:self action:@selector(fullscreenPressed:) forControlEvents:UIControlEventTouchUpInside];
_fullscreenButton.selected = isFull;
_fullscreenButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
_fullscreenButton.imageEdgeInsets = UIEdgeInsetsMake((40-37/2)/2, 10, (40-37/2)/2, 10);
}
return _fullscreenButton;
}
- (void)fullscreenPressed:(UIButton *)button {
if (isFull && self.isEmbedded) {
[self showEmbeddedVideo];
}
if (!isFull && self.isEmbedded) {
((TPWindow*)KEY_WINDOW).embeddedVideoGesture.enabled = YES;
}
if ([self.delegate respondsToSelector:@selector(enterFullScreen:)]) {
[self.delegate enterFullScreen:isFull];
}
button.selected = isFull;
}
- (UIButton *)cutPhotoBtn {
if (!_cutPhotoBtn) {
_cutPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[_cutPhotoBtn setImage:Image(@"video/photoCut.png") forState:UIControlStateNormal];
[_cutPhotoBtn addTarget:self action:@selector(cutPhotoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
_cutPhotoBtn.alpha = 0;
}
return _cutPhotoBtn;
}
- (UIButton *)standardButton {
if (!_standardButton) {
_standardButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_standardButton setTitle:@"标清" forState:UIControlStateNormal];
[_standardButton addTarget:self action:@selector(standardBtnClick:) forControlEvents:UIControlEventTouchUpInside];
_standardButton.titleLabel.textAlignment = NSTextAlignmentCenter;
[_standardButton setBackgroundImage:imageWithUIColor([UIColor clearColor])
forState:UIControlStateNormal];
// [_standardButton setBackgroundImage:imageWithUIColor([UIColor colorWithHexString:LINECOLOR])
// forState:UIControlStateSelected];
[_standardButton setEnabled:NO];
}
return _standardButton;
}
- (UIButton *)highButton {
if (!_highButton) {
_highButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_highButton setTitle:@"高清" forState:UIControlStateNormal];
[_highButton addTarget:self action:@selector(highBtnClick:) forControlEvents:UIControlEventTouchUpInside];
_highButton.titleLabel.textAlignment = NSTextAlignmentCenter;
[_highButton setBackgroundImage:imageWithUIColor([UIColor clearColor])
forState:UIControlStateNormal];
// [_highButton setBackgroundImage:imageWithUIColor([UIColor colorWithHexString:LINECOLOR])
// forState:UIControlStateSelected];
[_highButton setEnabled:NO];
}
return _highButton;
}
- (UIButton *)superButton {
if (!_superButton) {
_superButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_superButton setTitle:@"超清" forState:UIControlStateNormal];
[_superButton addTarget:self action:@selector(superBtnClick:) forControlEvents:UIControlEventTouchUpInside];
_superButton.titleLabel.textAlignment = NSTextAlignmentCenter;
[_superButton setBackgroundImage:imageWithUIColor([UIColor clearColor])
forState:UIControlStateNormal];
// [_superButton setBackgroundImage:imageWithUIColor([UIColor colorWithHexString:LINECOLOR])
// forState:UIControlStateSelected];
[_superButton setEnabled:NO];
}
return _superButton;
}
- (UISlider *)durationSlider {
if (nil == _durationSlider) {
_durationSlider = [[UISlider alloc] initWithFrame:CGRectZero];
[_durationSlider setThumbImage:Image(@"video/sliderThumb.png") forState:UIControlStateNormal];
_durationSlider.maximumTrackTintColor = [UIColor clearColor];
[_durationSlider addTarget:self action:@selector(durationSliderValueChanged:) forControlEvents:UIControlEventValueChanged];
[_durationSlider addTarget:self action:@selector(durationSliderTouchBegan:) forControlEvents:UIControlEventTouchDown];
// [_durationSlider addTarget:self action:@selector(durationSliderTouchEnded:) forControlEvents:UIControlEventTouchUpOutside];
[_durationSlider addTarget:self action:@selector(durationSliderTouchEnded:) forControlEvents:UIControlEventTouchUpInside];
}
return _durationSlider;
}
- (void)durationSliderTouchBegan:(UISlider *)slider {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideControls) object:nil];
[self.player pause];
self.playPasuButton.selected = YES;
}
- (void)durationSliderTouchEnded:(UISlider *)slider {
int temp = slider.value;
self.playPasuButton.selected = NO;
self.activityView.hidden = NO;
[self.activityView startAnimating];
[self.player seekToTime: CMTimeMakeWithSeconds(temp, 1)
toleranceBefore: kCMTimeZero
toleranceAfter: kCMTimeZero
completionHandler: ^(BOOL finished)
{
[self.player play];
[self performSelector:@selector(hideControls) withObject:nil afterDelay:5.f];
[self.activityView stopAnimating];
self.playPasuButton.selected = NO;
}];
}
- (void)durationSliderValueChanged:(UISlider *)slider {
}
- (TPLightView *)lightView {
if (nil == _lightView) {
_lightView = [[TPLightView alloc] initWithValue:(int)([UIScreen mainScreen].brightness*16)];
_lightView.alpha = 0;
}
return _lightView;
}
- (UIView *)playBackView {
if (_playBackView == nil) {
_playBackView = [[UIView alloc] initWithFrame:CGRectZero];
_playBackView.backgroundColor = [UIColor clearColor];
_playBackView.alpha = 0;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
imageView.image = Image(@"video/backImage.png");
[_playBackView addSubview:imageView];
[imageView makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(_playBackView);
}];
[_playBackView addSubview:self.playImage];
[self.playImage makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(_playBackView).offset(5);
make.centerX.equalTo(_playBackView);
make.size.mas_equalTo(CGSizeMake(55/2, 20));
}];
[_playBackView addSubview:self.totalLabel];
[_playBackView addSubview:self.timeSlider];
[self.timeSlider makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(_playBackView).offset(6);
make.right.equalTo(_playBackView).offset(-6);
make.bottom.equalTo(_playBackView).offset(-7);
make.height.mas_equalTo(1);
}];
[_playBackView addSubview:self.currLabel];
[_playBackView addSubview:self.cancelLabel];
[self.cancelLabel makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(_playBackView).offset(8);
make.right.equalTo(_playBackView).offset(-8);
make.bottom.equalTo(_playBackView).offset(-7);
make.height.mas_equalTo(20);
}];
[_playBackView addSubview:self.cancelImageView];
[self.cancelImageView makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(_playBackView).offset(5);
make.centerX.equalTo(_playBackView);
make.size.mas_equalTo(CGSizeMake(22, 22));
}];
}
return _playBackView;
}
- (UILabel *)cancelLabel {
if (_cancelLabel == nil) {
_cancelLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_cancelLabel.backgroundColor = [UIColor redColor];
_cancelLabel.textColor = [UIColor whiteColor];
_cancelLabel.font = appFont(9, NO);
_cancelLabel.text = @"松开手指,取消进退";
_cancelLabel.textAlignment = NSTextAlignmentCenter;
_cancelLabel.hidden = YES;
}
return _cancelLabel;
}
- (UIImageView *)cancelImageView {
if (nil == _cancelImageView) {
_cancelImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
_cancelImageView.image = Image(@"video/cancal.png");
_cancelImageView.hidden = YES;
}
return _cancelImageView;
}
- (UIProgressView *)timeSlider {
if (_timeSlider == nil) {
_timeSlider = [[UIProgressView alloc] initWithFrame:CGRectZero];
_timeSlider.progressTintColor = [UIColor colorWithHexString:@"0x5ca3e9"];
_timeSlider.trackTintColor = [UIColor clearColor];
// _timeSlider.maximumValue = floor(self.duration);
_timeSlider.userInteractionEnabled = NO;
}
return _timeSlider;
}
- (UIProgressView *)availablePro {
if (_availablePro == nil) {
_availablePro = [[UIProgressView alloc] initWithFrame:CGRectZero];
_availablePro.progressTintColor = [UIColor darkGrayColor];
_availablePro.trackTintColor = [UIColor clearColor];
_availablePro.userInteractionEnabled = NO;
}
return _availablePro;
}
- (UIImageView *)playImage {
if (_playImage == nil) {
_playImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 55/2, 20)];
}
return _playImage;
}
- (UILabel *)totalLabel {
if (_totalLabel == nil) {
_totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, 35, 75, 10)];
double totalTime = floor([self.player.currentItem duration].value);
_totalLabel.text = [NSString stringWithFormat:@"/%02.f:%02.f",floor(totalTime / 60.0),fmod(totalTime, 60.0)];
_totalLabel.font = appFont(9, NO);
_totalLabel.textColor = [UIColor whiteColor];
}
return _totalLabel;
}
- (UILabel *)currLabel {
if (_currLabel == nil) {
_currLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 35, 65, 10)];
double currentTime = floor(self.player.currentItem.currentTime.value);
_currLabel.text = [NSString stringWithFormat:@"%02.f:%02.f",floor(currentTime / 60.0),fmod(currentTime, 60.0)];
_currLabel.textAlignment = NSTextAlignmentRight;
_currLabel.font = appFont(9, NO);
_currLabel.textColor = [UIColor colorWithHexString:@"0x5ca3e9"];
}
return _currLabel;
}
- (UILabel *)barTotalLabel {
if (_barTotalLabel == nil) {
_barTotalLabel = [[UILabel alloc] initWithFrame:CGRectZero];
// _barTotalLabel.text = [NSString stringWithFormat:@"/%@",[self convertTime:CMTimeGetSeconds(self.playerItem.duration)]];
_barTotalLabel.font = appFont(9, NO);
_barTotalLabel.textColor = [UIColor whiteColor];
}
return _barTotalLabel;
}
- (UILabel *)barcurrLabel {
if (_barcurrLabel == nil) {
_barcurrLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_barcurrLabel.text = @"00:00";
_barcurrLabel.textAlignment = NSTextAlignmentRight;
_barcurrLabel.font = appFont(9, NO);
_barcurrLabel.textColor = [UIColor whiteColor];
}
return _barcurrLabel;
}
- (UIImage *)capture
{
UIGraphicsBeginImageContextWithOptions(self.playerView.bounds.size, self.playerView.opaque, 0.0);
[self.playerView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
- (void)cutPhotoBtnClick:(UIButton *)btn {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideControls) object:nil];
[self performSelector:@selector(hideControls) withObject:nil afterDelay:5.f];
if (isCut) {
return;
}
isCut = YES;
CMTime time = self.player.currentTime;
UIView *view = [[UIView alloc] initWithFrame:KEY_WINDOW.bounds];
view.backgroundColor = [UIColor whiteColor];
view.alpha = 0;
[KEY_WINDOW addSubview:view];
[UIView animateWithDuration:0.1 animations:^{
view.alpha = 1;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.1 animations:^{
view.alpha = 0;
} completion:^(BOOL finished) {
[view removeFromSuperview];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
AVURLAsset *myAsset = [[AVURLAsset alloc] initWithURL:self.contentURL options:nil];
AVAssetImageGenerator *myImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:myAsset];
myImageGenerator.appliesPreferredTrackTransform = YES;
//解决 时间不准确问题
myImageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
myImageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
[myImageGenerator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:time]] completionHandler:
^(CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error)
{
UIImage *img = [UIImage imageWithCGImage:image];
UIImageWriteToSavedPhotosAlbum(img, NULL, NULL, NULL);
NSLog(@"%@",error.description);
isCut = NO;
}];
});
// UIImageWriteToSavedPhotosAlbum([self snapshotInternalOnIOS7AndLater], NULL, NULL, NULL);
// [self performSelector:@selector(hideControls) withObject:nil afterDelay:5.f];
}];
}];
}
- (UIImage *)thumbnailImageAtCurrentTime
{
NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *myAsset = [[AVURLAsset alloc] initWithURL:self.contentURL options:opts];
AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:myAsset]; // 初始化AVAssetImageGenerator
imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
NSError *error = nil;
CMTime actualTime;
CGImageRef cgImage = [imageGenerator copyCGImageAtTime:self.player.currentTime actualTime:&actualTime error:&error]; // 从imageGenerator 取出时间戳
UIImage *image = [UIImage imageWithCGImage:cgImage];
return image;
}
- (UIImage*)snapshotInternalOnIOS7AndLater
{
UIGraphicsBeginImageContextWithOptions(self.playerView.bounds.size, NO, 1);
// Render our snapshot into the image context
[self.playerView drawViewHierarchyInRect:self.playerView.bounds afterScreenUpdates:YES]; // 该方法只有在iOS 7之后才可用
// Grab the image from the context
UIImage *complexViewImage = UIGraphicsGetImageFromCurrentImageContext();
// Finish using the context
UIGraphicsEndImageContext();
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
imageView.image = complexViewImage;
imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:imageView];
return complexViewImage;
}
- (UIImage *) imageOfPortionOfABiggerView
{
UIImage *image;
UIImage *wholeImage;
CGImageRef _image;
CGRect imageToExtractFrame;
CGFloat screenScale = [[UIScreen mainScreen] scale];
// have to scale the rect due to (I suppose) the screen's scale for Core Graphics.
imageToExtractFrame = CGRectApplyAffineTransform([self.playerView bounds], CGAffineTransformMakeScale(screenScale, screenScale));
UIGraphicsBeginImageContextWithOptions([self.view bounds].size, YES, screenScale);
[self.playerView drawViewHierarchyInRect: [self.playerView bounds] afterScreenUpdates: NO];
wholeImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// obtain a CGImage[Ref] from another CGImage, this lets me specify the rect to extract.
// However since the image is from a UIView which are all at 2x scale (retina) if you specify a rect in points CGImage will not take the screen's scale into consideration and will process the rect in pixels. You'll end up with an image from the wrong rect and half the size.
_image = CGImageCreateWithImageInRect([wholeImage CGImage], imageToExtractFrame);
wholeImage = nil;
// have to specify the image's scale due to CGImage not taking the screen's scale into consideration.
image = [UIImage imageWithCGImage: _image scale: screenScale orientation: UIImageOrientationUp];
CGImageRelease(_image);
return image;
}
- (void)panHandler:(UIPanGestureRecognizer *)pan {
if (self.isEmbedded && !isFull) {
return;
}
switch (pan.state) {
case UIGestureRecognizerStateBegan:
beginPoint = [pan locationInView:self.view];
tempPoint = beginPoint;
value = [UIScreen mainScreen].brightness;
sysV = volumeViewSlider.value;
directionString = nil;
_totalLabel.text = [NSString stringWithFormat:@"/%@",_totalTime];
break;
case UIGestureRecognizerStateChanged:
movePoint = [pan locationInView:self.view];
if (directionString == nil) {
if (fabs(movePoint.y - beginPoint.y) > fabs(movePoint.x - beginPoint.x) && fabs(movePoint.y - beginPoint.y) > 20) {
directionString = @"1";//竖直
}else if (fabs(movePoint.x - beginPoint.x) > fabs(movePoint.y - beginPoint.y) && fabs(movePoint.x - beginPoint.x) > 20) {
if (isLive) {
return;
}
directionString = @"0";//水平
}
}else {
if ([directionString isEqualToString:@"1"]) {
if ([pan locationInView:self.view].x <= rect_screen.size.width/2) {//亮度
_lightView.alpha = 1;
CGFloat tmp = value +0.05*((beginPoint.y - movePoint.y)/10);
if (tmp > 1.0) {
tmp = 1.0;
}else if (tmp < 0) {
tmp = 0;
}
[UIScreen mainScreen].brightness = tmp;
[_lightView setValue:(int)(tmp*16)];
}else {
CGFloat tmp = sysV+0.05*((beginPoint.y - movePoint.y)/10);
if (tmp > 1.0) {
tmp = 1.0;
}else if (tmp < 0) {
tmp = 0;
}
[volumeViewSlider setValue:tmp animated:YES];
}
}else { //快进快退
self.playBackView.alpha = 1;
if (([pan locationInView:self.view].x >= 0 && [pan locationInView:self.view].x <= 20) || ([pan locationInView:self.view].x >= rect_screen.size.width - 20 && [pan locationInView:self.view].x <= rect_screen.size.width)) {
isCancel = YES;
self.currLabel.hidden = YES;
self.totalLabel.hidden = YES;
self.timeSlider.hidden = YES;
self.playImage.hidden = YES;
self.cancelImageView.hidden = NO;
self.cancelLabel.hidden = NO;
}else {
double totalTime = CMTimeGetSeconds(self.playerItem.duration);
double currentTime = CMTimeGetSeconds(self.playerItem.currentTime);
double temp = (currentTime + ((movePoint.x - beginPoint.x)/6*(totalTime/120.0)));
if (temp < 0) {
temp = 0;
}else if (temp > totalTime) {
temp = totalTime;
}
self.currLabel.text = [self convertTime:temp];
if (movePoint.x < tempPoint.x) {
self.playImage.image = Image(@"video/playBack.png");
}else if (tempPoint.x < movePoint.x){
self.playImage.image = Image(@"video/playForword.png");
}
[self.timeSlider setProgress:(temp/totalTime) animated:YES];
tempPoint = movePoint;
isCancel = NO;
self.currLabel.hidden = NO;
self.totalLabel.hidden = NO;
self.timeSlider.hidden = NO;
self.playImage.hidden = NO;
self.cancelImageView.hidden = YES;
self.cancelLabel.hidden = YES;
}
}
}
break;
case UIGestureRecognizerStateEnded:
{
if ([directionString isEqualToString:@"0"]) {
double totalTime = CMTimeGetSeconds(self.playerItem.duration);
double currentTime = CMTimeGetSeconds(self.playerItem.currentTime);
double temp = (currentTime + ((movePoint.x - beginPoint.x)/6*(totalTime/120.0)));
if (temp < 0) {
temp = 0;
}else if (temp > totalTime) {
temp = totalTime;
}
if (isCancel == NO) {
self.activityView.hidden = NO;
[self.activityView startAnimating];
[self.player pause];
[self.player seekToTime: CMTimeMakeWithSeconds(temp, 1)
toleranceBefore: kCMTimeZero
toleranceAfter: kCMTimeZero
completionHandler: ^(BOOL finished)
{
[self.player play];
[self.activityView stopAnimating];
self.playPasuButton.selected = NO;
}];
}
[UIView animateWithDuration:1 animations:^{
self.playBackView.alpha = 0;
} completion:^(BOOL finished) {
}];
}else if ([directionString isEqualToString:@"1"]) {
if ([pan locationInView:self.view].x <= rect_screen.size.width/2) {
[UIView animateWithDuration:1.5 animations:^{
self.lightView.alpha = 0;
} completion:^(BOOL finished) {
}];
}
}
}
break;
default:
break;
}
[pan setTranslation:CGPointMake(0, 0) inView:self.view];
}
- (void)selfDealloc {
if (!isLive && !isBlankString(self.contentUrlDic[@"standard"]))
[self addMemoryPoint];
_delegate = nil;
[self.player pause];
[self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
[self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
[self.player replaceCurrentItemWithPlayerItem:nil];
self.playerItem = nil;
self.contentUrlDic = nil;
self.player = nil;
self.playerView = nil;
[self.playerView.player removeTimeObserver:self.playbackTimeObserver];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)addMemoryPoint {
CGFloat point = self.player.currentTime.value/self.player.currentTime.timescale+1;
CGFloat totalSecond = self.playerItem.duration.value/self.playerItem.duration.timescale;// 转换成秒
NSLog(@"%f %f", point,totalSecond);
if (point < (self.playerItem.duration.value/self.playerItem.duration.timescale)) {
NSMutableDictionary *pointDic = [NSMutableDictionary dictionary];
[pointDic setObject:self.contentUrlDic[@"standard"] forKey:@"name"];
[pointDic setObject:[NSString stringWithFormat:@"%f", point] forKey:@"point"];
NSMutableArray *pointArray = [NSMutableArray arrayWithArray:[TPUserDefault instance].memoryPointArray];
if (pointArray.count >= 10) {
[pointArray removeObjectAtIndex:0];
}
[pointArray addObject:pointDic];
[TPUserDefault instance].memoryPointArray = pointArray;
}
}
- (void)standardBtnClick:(UIButton *)button {
[self changeBitrate:@"standard"];
}
- (void)highBtnClick:(UIButton *)button {
[self changeBitrate:@"high"];
}
- (void)superBtnClick:(UIButton *)button {
[self changeBitrate:@"super"];
}
- (void)changeBitrate:(NSString *)rate {
if (!isBlankString(self.contentUrlDic[rate])) {
if ([self.contentUrlDic[rate] isEqualToString:self.contentURL.absoluteString]) {
return;
}
NSLog(@"change to %@", self.contentUrlDic[rate]);
if ([rate isEqualToString:@"standard"]) {
_standardButton.selected = YES;
_highButton.selected = NO;
_superButton.selected = NO;
}
else if ([rate isEqualToString:@"high"]) {
_standardButton.selected = NO;
_highButton.selected = YES;
_superButton.selected = NO;
}
else if ([rate isEqualToString:@"super"]) {
_standardButton.selected = NO;
_highButton.selected = NO;
_superButton.selected = YES;
}
[self.rateButton setTitle:[self changeStr:rate] forState:UIControlStateNormal];
[TPUserDefault instance].videoDefinition = rate;
[self rateButtonClick:self.rateButton];
[self.player pause];
self.activityView.hidden = NO;
[self.activityView startAnimating];
[self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
[self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
if (!isLive && self.playbackTimeObserver)
changePoint = self.player.currentTime.value/self.player.currentTime.timescale;
if (self.playbackTimeObserver) {
[self.playerView.player removeTimeObserver:self.playbackTimeObserver];
self.playbackTimeObserver = nil;
}
self.contentURL = [NSURL URLWithString:self.contentUrlDic[rate]];
[self.player replaceCurrentItemWithPlayerItem:nil];
self.playerItem = nil;
self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.contentUrlDic[rate]]];
[self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
[self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
[self.player replaceCurrentItemWithPlayerItem:self.playerItem];
if (!isLive) {
self.durationSlider.value = changePoint;
self.activityView.hidden = NO;
[self.activityView startAnimating];
[self.player seekToTime: CMTimeMakeWithSeconds(changePoint, 1)
toleranceBefore: kCMTimeZero
toleranceAfter: kCMTimeZero
completionHandler: ^(BOOL finished)
{
[self.player play];
}];
}
else
[self.player play];
}
}
# pragma mark - Getters
- (BOOL)isFullscreen {
return _movieFullscreen;
}
# pragma mark - Setters
- (BOOL)videoIsLiving {
NSString *url = [self.contentURL absoluteString];
if ([url isMatchedByRegex:@"m3u8"]) {
return YES;
}else {
return NO;
}
}
- (void)relayoutSubViewForScreen:(CGRect)rect fullScreen:(BOOL)fullScreen{
isFull = fullScreen;
_movieFullscreen = isFull;
self.fullscreenButton.selected = isFull;
if (fullScreen&&isShow) {
self.cutPhotoBtn.alpha = 1;
self.rateButton.alpha = 1;
}else {
self.cutPhotoBtn.alpha = 0;
self.rateButton.alpha = 0;
}
if (self && self.view.superview) {
[self.view remakeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(rect.origin.x);
make.top.mas_equalTo(rect.origin.y);
make.size.mas_equalTo(rect.size);
}];
if (!fullScreen && !self.isEmbedded) {
self.originRect = rect;
}
[self.playerView remakeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
}
}
- (void)moviePlayDidEnd:(NSNotification *)notification {
if ([self.delegate respondsToSelector:@selector(playFinish)]) {
[self.delegate playFinish];
}
}
// KVO方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
AVPlayerItem *playerItem = (AVPlayerItem *)object;
if ([keyPath isEqualToString:@"status"]) {
if ([playerItem status] == AVPlayerStatusReadyToPlay) {
NSLog(@"AVPlayerStatusReadyToPlay");
CGFloat totalSecond = playerItem.duration.value;// 转换成秒
[self showControls];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.activityView stopAnimating];
});
isLoading = NO;
if ([self videoIsLiving] && totalSecond < 30) {
self.availablePro.hidden = YES;
self.durationSlider.userInteractionEnabled = NO;
self.barcurrLabel.text = @"";
self.barTotalLabel.text = @"直播中";
self.barTotalLabel.textAlignment = NSTextAlignmentRight;
isLive = YES;
}else {
isLive = NO;
CGFloat totalSecond = playerItem.duration.value/playerItem.duration.timescale;// 转换成秒
_totalTime = [self convertTime:totalSecond];// 转换成播放时间
self.barTotalLabel.text = [NSString stringWithFormat:@"/%@",_totalTime];
self.durationSlider.maximumValue = totalSecond;
[self monitoringPlayback:self.playerItem];// 监听播放状态
}
if (isFirstIn) {
NSMutableArray *pointArray = [NSMutableArray arrayWithArray:[TPUserDefault instance].memoryPointArray];
NSLog(@"point num: %ld", pointArray.count);
NSDictionary *deleteItem;
for (NSDictionary *dic in pointArray) {
if ([dic[@"name"] isEqualToString:self.contentUrlDic[@"standard"]]) {
NSLog(@"seek to %@", dic[@"point"]);
[self.player pause];
self.durationSlider.value = [dic[@"point"] intValue];
self.activityView.hidden = NO;
[self.activityView startAnimating];
[self.player seekToTime: CMTimeMakeWithSeconds([dic[@"point"] intValue], 1)
toleranceBefore: kCMTimeZero
toleranceAfter: kCMTimeZero
completionHandler: ^(BOOL finished)
{
[self.activityView stopAnimating];
[self.player play];
}];
deleteItem = dic;
break;
}
}
if (deleteItem) {
[pointArray removeObject:deleteItem];
[TPUserDefault instance].memoryPointArray = pointArray;
}
isFirstIn = NO;
}
[self.player play];
} else if ([playerItem status] == AVPlayerStatusFailed) {
NSLog(@"AVPlayerStatusFailed");
}
} else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
if (isLive) {
return;
}
NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
// NSLog(@"Time Interval:%f",timeInterval);
CMTime duration = self.playerItem.duration;
CGFloat totalDuration = CMTimeGetSeconds(duration);
if (!isnan(timeInterval / totalDuration)) {
if (timeInterval > totalDuration) {
timeInterval = totalDuration;
}
[self.availablePro setProgress:timeInterval / totalDuration animated:YES];
}
}
}
- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
if (!self.playbackTimeObserver) {
__weak typeof(self) weakSelf = self;
self.playbackTimeObserver = [self.playerView.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;// 计算当前在第几秒
// NSLog(@"%f",currentSecond);
[weakSelf.durationSlider setValue:currentSecond animated:YES];
NSString *timeString = [weakSelf convertTime:currentSecond];
weakSelf.barcurrLabel.text = timeString;
}];
}
}
- (NSString *)convertTime:(CGFloat)second{
NSString *str_hour ;
NSString *str_minute;
NSString *str_second;
NSString *format_time;
int seconds = (int)second;
if (second/3600 >= 1) {
isHours = YES;
str_hour = [NSString stringWithFormat:@"%02d",seconds/3600];
str_minute = [NSString stringWithFormat:@"%02d",(seconds%3600)/60];
str_second = [NSString stringWithFormat:@"%02d",seconds%60];
format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
[self remakeLabel];
} else {
if (isHours) {
str_hour = [NSString stringWithFormat:@"%02d",seconds/3600];
str_minute = [NSString stringWithFormat:@"%02d",(seconds%3600)/60];
str_second = [NSString stringWithFormat:@"%02d",seconds%60];
format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
}else {
str_minute = [NSString stringWithFormat:@"%02d",(seconds%3600)/60];
str_second = [NSString stringWithFormat:@"%02d",seconds%60];
format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
}
}
return format_time;
}
- (NSDateFormatter *)dateFormatter {
if (!_dateFormatter) {
_dateFormatter = [[NSDateFormatter alloc] init];
}
return _dateFormatter;
}
- (void)remakeLabel {
[self.barTotalLabel remakeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.availablePro);
make.top.equalTo(self.availablePro.bottom).offset(3);
make.size.mas_equalTo(CGSizeMake(45, 10));
}];
[self.barcurrLabel remakeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.barTotalLabel.left);
make.top.equalTo(self.barTotalLabel);
make.size.mas_equalTo(CGSizeMake(45, 10));
}];
}
- (NSTimeInterval)availableDuration {
NSArray *loadedTimeRanges = [[self.playerView.player currentItem] loadedTimeRanges];
CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
return result+1;
}
- (void)setFullscreen:(BOOL)fullscreen {
[self setFullscreen:fullscreen animated:NO];
}
- (void)setFullscreen:(BOOL)fullscreen animated:(BOOL)animated {
_movieFullscreen = fullscreen;
}
- (void)tapHandler:(id)sender {
if (self.isEmbedded && !isFull) {
[self embeddedVideoEnterFullScreen];
return;
}
if (isLoading) {
return;
}
if (isShow) {
[self hideControls];
}else {
[self showControls];
}
}
- (void)hideControls {
if (self.isEmbedded && !isFull) {
return;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideControls) object:nil];
if (self.rateButton.selected) {
[self rateButtonClick:self.rateButton];
}
[UIView animateWithDuration:0.35 animations:^{
self.bottonView.alpha = 0;
self.cutPhotoBtn.alpha = 0;
self.rateButton.alpha = 0;
self.rateView.alpha = 0;
self.closeButton.alpha = 0;
isShow = NO;
}];
}
- (void)showControls {
[UIView animateWithDuration:0.35 animations:^{
self.bottonView.alpha = 1;
if (isFull) {
self.cutPhotoBtn.alpha = 1;
self.rateButton.alpha = 1;
self.rateView.alpha = 1;
}
self.closeButton.alpha = 1;
isShow = YES;
} completion:^(BOOL finished) {
[self performSelector:@selector(hideControls) withObject:nil afterDelay:5.f];
}];
}
- (void)controlTapGesture:(BOOL)enabled {
tap.enabled = enabled;
}
#pragma mark - embeddedVideoControls
- (void)showEmbeddedVideo {
[self showControls];
self.bottonView.hidden = YES;
self.cutPhotoBtn.hidden = YES;
self.isEmbedded = YES;
self.rateView.hidden = YES;
}
- (void)dismissEmbeddedVideo {
self.bottonView.hidden = NO;
self.cutPhotoBtn.hidden = NO;
self.isEmbedded = NO;
self.rateView.hidden = NO;
}
- (void)embeddedVideoEnterFullScreen {
self.bottonView.hidden = NO;
self.cutPhotoBtn.hidden = NO;
self.rateView.hidden = NO;
((TPWindow*)KEY_WINDOW).embeddedVideoGesture.enabled = NO;
if ([self.delegate respondsToSelector:@selector(enterFullScreen:)]) {
[self.delegate enterFullScreen:isFull];
}
}
//- (BOOL)shouldAutorotate {
// return YES;
//}
//
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
// return UIInterfaceOrientationMaskAllButUpsideDown;
//}
//
//- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
// return UIInterfaceOrientationPortrait | UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight;
//}
//
//- (void)statusBarOrientationWillChange:(NSNotification *)note {
// UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
//
// if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
// orientation = UIInterfaceOrientationPortrait;
// [self relayoutSubViewForScreen:vedioFrame];
// }else {
//// orientation = UIInterfaceOrientationLandscapeLeft;
// [self relayoutSubViewForScreen:KEY_WINDOW.bounds];
// }
//}
//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
// return YES;
//}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
|