自定义一个视屏播放器

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

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

#import "CustomAVPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

#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<NSString *,id> *)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<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    if (_backView.alpha != 1) {
        

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

- (void)touchesMoved:(NSSet<UITouch *> *)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<UITouch *> *)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;//计算缓存总进度

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容