自定义一个视屏播放器

AVPlayer可以自定义视屏播放器的样式
其中主要是理解CMTime的用法,CMTime是一个结构体,它有2个属性很重要,一个是value:表示总共有多少帧,一个是timeScale这个表示每秒钟多少帧
value/timeScale得到秒(我们想要的时间)
ps:支持手势双击暂停和开始播放,支持左右滑动
快进快退
note : 当横屏的时候屏幕的宽高要调换

//
//  CustomAVPlayer.m
//  PlayOnNet
//
//  Created by ios on 16/9/3.
//  Copyright © 2016年 fenglei. All rights reserved.
//

#import "CustomAVPlayer.h"
#import 
#import 

#define KScreenHeight [[UIScreen mainScreen]bounds].size.height
#define KScreenWidth  [[UIScreen mainScreen]bounds].size.width



@interface CustomAVPlayer ()

@property (nonatomic, strong)AVPlayer *player;//播放对象

@property (nonatomic, strong)AVPlayerItem *playerItem;//播放资源对象
@property (nonatomic, strong)UIView *backView;//背景视图

@property (nonatomic, strong)UIButton *backButton;//返回按钮

@property (nonatomic, strong)UILabel *currentTimeLabel;//当前播放时间label;
@property (nonatomic, strong)UILabel *totalTimeLabel;//总时间

@property (nonatomic, strong)UISlider *currentSlider;//当前播放进度

@property (nonatomic, strong)UIProgressView *availableProgress;//已缓存的进度
@property (nonatomic, strong)UIButton *playButton;//播放和暂停

@property (nonatomic, strong)NSTimer *timer;//定时器



@end


@implementation CustomAVPlayer

- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    
    
    [self createSubviews];
    
    _timer  = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(moveSlider:) userInfo:nil repeats:YES];
    

}

#pragma  mark - 创建子视图
- (void)createSubviews{
    
    
    
    //初始化媒体播放对象
    self.playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:@"http://vf1.mtime.cn/Video/2012/04/23/mp4/120423212602431929.mp4"]];
    
    self.player = [AVPlayer  playerWithPlayerItem:self.playerItem];
    
    //创建AVPlayerLayer
    AVPlayerLayer *AVLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    AVLayer.frame = CGRectMake(0, 0, self.view.layer.bounds.size.height, self.view.layer.bounds.size.width);
    AVLayer.videoGravity = AVLayerVideoGravityResize;
    [self.view.layer addSublayer:AVLayer];
    [_player play];
    
    //创建背景视图
    [self createbackView];
    
    
    //播放完成时候的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(finishPlay:) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
    
    
    //kVO监听已经缓存的进度(是否达到播放要求)
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}

//创建背景视图
- (void)createbackView {
    
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenHeight, KScreenWidth)];
    self.backView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.backView];
    
    //返回按钮
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backButton.frame = CGRectMake(10, 20, 40, 40);
    
    [_backButton setImage:[UIImage imageNamed:@"gobackBtn"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:_backButton];

    //创建子视图
    
    
#pragma mark -创建子控件
    [self createProgressView];
    [self createSlider];
    [self createLabel];
    [self createPlayButton];
    //添加手势
    [self createGesture];
    //当用户不在操作屏幕的时候自动隐藏背景视图
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            _backView.alpha = 0;
        }];
        
        
    });
    
    
}

//当前时间进度
- (void)createSlider {
    
    self.currentSlider = [[UISlider alloc]initWithFrame:CGRectMake(100, KScreenWidth - 60, KScreenHeight - 300,  31)];
    _currentSlider.maximumValue = 1;
    _currentSlider.minimumValue = 0;
    [_currentSlider setThumbImage:[UIImage imageNamed:@"iconfont-yuan"] forState:UIControlStateNormal];
    [_currentSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [_currentSlider setMaximumTrackTintColor:[UIColor clearColor]];
    [_currentSlider setMinimumTrackTintColor:[UIColor orangeColor]];
    [_backView addSubview:_currentSlider];
    
}

//时间的label
- (void)createLabel {
    
    //当前的时间
    self.currentTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_currentSlider.frame) + 10, CGRectGetMinY(_currentSlider.frame)+5, 60, 20)];
    
    _currentTimeLabel.text = @"00:00/";
    _currentTimeLabel.backgroundColor = [UIColor redColor];
    _currentTimeLabel.textColor = [UIColor whiteColor];
    _currentTimeLabel.font = [UIFont boldSystemFontOfSize:17];
    [self.backView addSubview:_currentTimeLabel];
    
    //总时间
    self.totalTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_currentTimeLabel.frame)+10, _currentTimeLabel.frame.origin.y, 60, 20)];
    
    _totalTimeLabel.text = @"00:00";
    _totalTimeLabel.textColor = [UIColor whiteColor];
    
    [_backView addSubview:_totalTimeLabel];
    
    
}

//创建一个已缓存的进度条
- (void)createProgressView {
    
    self.availableProgress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    _availableProgress.frame = CGRectMake(102, KScreenWidth - 60 +15 , KScreenHeight - 300+2, 2);
    
    //进度颜色
    _availableProgress.progressTintColor = [UIColor colorWithRed:67/255.0 green:67/255.0 blue:67/255.0 alpha:1];
    
    //进度条当前的颜色
    _availableProgress.trackTintColor = [UIColor colorWithRed:154/255.0 green:154/255.0 blue:154/255.0 alpha:1];
    [_backView addSubview:_availableProgress];
    
}

//播放和暂停的按钮
- (void)createPlayButton {
    
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButton.frame = CGRectMake(15, CGRectGetMinY(_currentSlider.frame), 30, 30);
    [_playButton setImage:[UIImage imageNamed:@"pauseBtn@2x"] forState:UIControlStateNormal];
    
    [_backView addSubview:_playButton];
    
    [_playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
}


#pragma  mark - 定时器
//滑动滑块和计算当前时间
- (void)moveSlider:(NSTimer *)timer{
    
    
    
    //帧数不为0(能播放的状态)
    if (_playerItem.duration.timescale != 0) {
        
        _currentSlider.value = CMTimeGetSeconds([_playerItem currentTime]) / (_playerItem.duration.value / _playerItem.duration.timescale);//当前进度
        //当前时长进度progress
        NSInteger proMin = (NSInteger)CMTimeGetSeconds([_player currentTime]) / 60;//当前秒
        NSInteger proSec = (NSInteger)CMTimeGetSeconds([_player currentTime]) % 60;//当前分钟

        NSInteger durMin = (NSInteger)_playerItem.duration.value / _playerItem.duration.timescale / 60;//总秒
        NSInteger durSec = (NSInteger)_playerItem.duration.value / _playerItem.duration.timescale % 60;//总分钟
        
        _totalTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",durMin, durSec];
        
        _currentTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld/",proMin, proSec];
        
    }
    
    
}



#pragma  mark - 响应事件

//返回按钮
- (void)backAction {
    
    
    [self.player pause];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//播放按钮的响应事件
- (void)playAction :(UIButton *)button {
    
    if (_player.rate == 0) {
        
        [_player play];
        [_playButton setImage:[UIImage imageNamed:@"pauseBtn@2x"] forState:UIControlStateNormal];

        
    }else if(_player.rate == 1) {
        
        [_player pause];
        [_playButton setImage:[UIImage imageNamed:@"playBtn@2x"] forState:UIControlStateNormal];


    }
   
    button.selected = !button.selected;

}

//滑动条的响应事件
- (void)sliderAction:(UISlider *)slider {
    
    
    //视频的总时间
    CGFloat total = (CGFloat)_playerItem.duration.value / _playerItem.duration.timescale;
    
    //当前的进度对应的播放时间
    NSInteger  time = floorf(total * slider.value);//求不大于传入值的最大整数
    
    CMTime currentTime = CMTimeMake(time, 1);
    
    //暂停
    [_player pause];

    
    //当前视屏滑到指定位置播放
    [_player seekToTime:currentTime completionHandler:^(BOOL finished) {
       
        [_player  play];

    }];
}
//手势(双击)响应事件
-(void)tapAction {
    
    
    //暂停的状态
    if (_player.rate ==  0) {
        
        [_player play];
        [_playButton setImage:[UIImage imageNamed:@"pauseBtn@2x"] forState:UIControlStateNormal];
        
    }else if (_player.rate == 1){//播放的状态
        
        [_player pause];
        [_playButton setImage:[UIImage imageNamed:@"playBtn@2x"] forState:UIControlStateNormal];
        
    }
    
    
}


#pragma  mark - 通知
//结束播放时候的通知
- (void)finishPlay:(id)sender {
    
    

    
    
}

#pragma  mark - KVO监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        //总缓存
        NSTimeInterval totalCashe = [self availabelDuration];
        
        //视屏总时长
        CMTime duration = _playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        
        //求缓存进度条
        _availableProgress.progress =  totalCashe / totalDuration;
        
        
        
    }
    
    
    
}

//获取缓存区域
- (NSTimeInterval)availabelDuration {
    
    NSArray *loadedTimeRanges = [[_player currentItem] loadedTimeRanges];
    
    //获取缓存区域
    CMTimeRange range = [loadedTimeRanges.firstObject  CMTimeRangeValue];
    
    float startSeconds = CMTimeGetSeconds(range.start);
    
    float durationSeconds = CMTimeGetSeconds(range.duration);
    
    NSTimeInterval total = startSeconds + durationSeconds;//计算缓存总进度
    
    return total;
}


#pragma  mark - 手势
- (void)createGesture {
    
    //双击
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    tap.numberOfTapsRequired = 2;
    [_backView addGestureRecognizer:tap];
    

    
    
    
    
}



#pragma  mark - 屏幕旋转
- (BOOL)shouldAutorotate {
    
    
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
    
    return UIInterfaceOrientationMaskLandscape;//只支持横屏
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    
    
    return UIInterfaceOrientationLandscapeRight;//默认横屏向右
}

- (BOOL)prefersStatusBarHidden {
    
    
    return NO;//不隐藏状态栏
}



#pragma  mark - 点击屏幕的响应事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    if (_backView.alpha != 1) {
        

    
    [UIView animateWithDuration:0.5 animations:^{
                
        _backView.alpha = 1;
    }];
    
    }
    
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    
    //获取滑动后的x轴偏移量
    //1>获取最先点击的点
    CGPoint prePoint = [[touches anyObject] previousLocationInView:_backView];
    //2>最后手指离开屏幕的那个点
    CGPoint lastPoint = [[touches anyObject]locationInView:_backView];
    //x轴偏移量
    CGFloat offsetX = lastPoint.x  - prePoint.x;
    

    if (offsetX >= 20 || offsetX <= -20) {
    
    
    //滑动的百分比
    CGFloat percent = offsetX / KScreenHeight;
    
    //视频的总时间
    CGFloat totalTime = (_playerItem.duration.value / _playerItem.duration.timescale);
    CGFloat currentTime = CMTimeGetSeconds([_playerItem currentTime]);
    
    currentTime = totalTime * percent + currentTime;
    
    if (currentTime >= totalTime) {
        
        [_player pause];
        return;
    }
    
    CMTime  time = CMTimeMake(currentTime, 1);
 
    [_player pause];
   
    
    [_player seekToTime:time completionHandler:^(BOOL finished) {
        
        [_player play];
    }];

}
   
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
    
    CGFloat currentTime = CMTimeGetSeconds([_playerItem currentTime]);

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((currentTime+7) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.5 animations:^{
           
            _backView.alpha = 0;
        }];
        
        
    });
     
//    [_backView performSelector:@selector(setAlpha:) withObject:[NSNumber numberWithInt:0] afterDelay:currentTime + 7];
    
    
}

#pragma  mark - 销毁通知和KVO
- (void)dealloc {
    
    
    [_timer invalidate];
    _timer = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [_playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    
    
    
}





@end

其中很重要的一个是loadedTimeRanges属性,它是一个数组。

    //获取缓存区域
    CMTimeRange range = [loadedTimeRanges.firstObject  CMTimeRangeValue];
    
   //获取缓存的开始
    float startSeconds = CMTimeGetSeconds(range.start);
    
    float durationSeconds = CMTimeGetSeconds(range.duration);
    
    NSTimeInterval total = startSeconds + durationSeconds;//计算缓存总进度

有些地方写的不好,各位看官随意,多多体谅

你可能感兴趣的:(自定义一个视屏播放器)