使用AVPlaer创建视屏播放器

本文档介绍了如何在PlayerView.m文件中利用AVPlayer来创建一个视频播放器,并且详细说明了在ZQYSliderView中实现进度滑动条的操作步骤。

//#PlayerView.m文件中

#import "PlayerView.h"
#import <AVFoundation/AVFoundation.h>
#import "ZQYSliderView.h"

@interface PlayerView()

@property(nonatomic,copy)NSString * urlStr;

@property(nonatomic,strong)AVPlayer * player;

//进度管理视图
@property(nonatomic,strong)ZQYSliderView * slider;

@property(nonatomic,strong)UILabel * timeLabel;

@end


@implementation PlayerView

+(PlayerView *)playerViewWithFrame:(CGRect)frame URL:(NSString *)urlStr{
    
    PlayerView * pv =[[PlayerView alloc]initWithFrame:frame];
    pv.frame = frame;
    pv.urlStr = urlStr;
    pv.backgroundColor = [UIColor blueColor];
    return pv;
}

-(instancetype)initWithFrame:(CGRect)frame{
    
    if (self =[super initWithFrame:frame]) {
        //创建滑动进度条
        _slider =[[ZQYSliderView alloc]initWithFrame:CGRectMake(35, frame.size.height - 15, frame.size.width - 80, 5)];
        [self addSubview:_slider];
        
        [_slider setProgressChangeBlock:^(CGFloat progress) {
            //视频跳转到
            int time = CMTimeGetSeconds(self.player.currentItem.duration) * progress;
            [self.player seekToTime:CMTimeMake(time * NSEC_PER_SEC, NSEC_PER_SEC) completionHandler:nil];
            
        }];
        
        
        [_slider setStatusBlcok:^(kProgressStatus status) {
            if (status == kProgressStatusDrag) {
                [self.player play];
            }else{
                [self.player pause];
            }
        }];
        
        
        //按钮
        UIButton * playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        playButton.frame = CGRectMake(6, _slider.center.y - 8+0.8 , 13, 13);
        [playButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        [playButton addTarget:self action:@selector(changePlayStatus:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:playButton];
        
        //监听播放进度
        __weak typeof(self) weakSelf = self;
        [_player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1, NSEC_PER_SEC) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
            //获得当前的播放比列 currentTime / duration
            CGFloat progress = CMTimeGetSeconds(self.player.currentTime)/CMTimeGetSeconds(self.player.currentItem.duration);
            weakSelf.slider.progress = progress;
            NSLog(@"%f",progress);
        }];
        
        
        //获取视屏时间
        int totalTime = CMTimeGetSeconds(_player.currentItem.duration);
        
        
        //创建显示时间的Label
        self.timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(frame.size.width -50, _slider.center.y - 8+0.8-4 , 50, 20)];
        _timeLabel.textAlignment =UITextAlignmentCenter;
        _timeLabel.font = [UIFont systemFontOfSize:15];
        _timeLabel.text = [self timeStringWithSeconds:totalTime];
        [self addSubview:self.timeLabel];



        
    }
    return self;
}

- (NSString *)timeStringWithSeconds:(NSInteger)seconds{
    int totalTime = seconds;
    int hour = totalTime / 60 / 60;
    int min = totalTime / 60 - hour*60;
    int sec = totalTime % 60;
    
    NSString *time;
    if (hour > 0) {
        time = [NSString stringWithFormat:@"%02d:%02d:%02d",-hour,-min,-sec];
    }else{
        time = [NSString stringWithFormat:@"%02d:%02d",-min,-sec];
    }
    NSLog(@"%d,%@",seconds,time);
    return time;
}

//更改按钮的图片
-(void)changePlayStatus:(UIButton*)sender{
    if (self.player.rate == 0) {
        //在播放
        [sender setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        [self play];
    }else{
        //在暂停
        [sender setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        [self pause];
    }
}


-(void)setUrlStr:(NSString *)urlStr{
    _urlStr = urlStr;
    [self initPlayer];
}

//init界面
-(void)initPlayer{
    NSLog(@"herer");
    
    //创建播放器
    self.player = [AVPlayer playerWithURL:[NSURL URLWithString:_urlStr]];
    //创建PlayerLayer
    AVPlayerLayer * layer = [AVPlayerLayer playerLayerWithPlayer:_player];
    layer.frame = self.bounds;
    //填满
    layer.videoGravity =  AVLayerVideoGravityResize;
    [self.player play];
    [self.layer insertSublayer:layer atIndex:0];
    
    //监听播放进度
    [_player addPeriodicTimeObserverForInterval:CMTimeMake(1 , NSEC_PER_SEC) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        CGFloat progress = CMTimeGetSeconds(self.player.currentItem.currentTime) / CMTimeGetSeconds(self.player.currentItem.duration);
        
        self.slider.progress = progress;
    }];
}



-(void)play{
    [_player play];
}

-(void)pause{
    [_player pause];
}

//在ZQYSliderView文件中创建滑动条


#import "ZQYSliderView.h"

@interface ZQYSliderView()

@property(nonatomic,strong)UIImageView * backGroundView;
//进度视图
@property(nonatomic,strong)UIImageView * tintView;

//圆点
@property(nonatomic,strong)UIImageView * dotView;

@end

@implementation ZQYSliderView


-(instancetype)initWithFrame:(CGRect)frame{
    
    if (self =[super initWithFrame:frame]) {
        
        //背景视图
        _backGroundView = [self viewWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) color:[UIColor lightGrayColor]];
        
        //进度视图
        _tintView = [self viewWithFrame:CGRectMake(0, 0, 0, frame.size.height) color:[UIColor orangeColor]];
        
        //圆点
        _dotView = [self viewWithFrame:CGRectMake(0,0,4 * frame.size.height,20) color:[UIColor whiteColor]];
        _dotView.layer.cornerRadius = _dotView.frame.size.width/2.0;
        _dotView.center = CGPointMake(_tintView.frame.size.width, _tintView.frame.size.height/2.0);
        
        //添加拖动手势
        UIPanGestureRecognizer * panGes = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGes:)];
        [self addGestureRecognizer:panGes];
        
    }
    return self;
}

//创建一个imageView;
-(UIImageView*)viewWithFrame:(CGRect)frame color:(UIColor*)color{
    UIImageView *image = [[UIImageView alloc]initWithFrame:frame];
    image.backgroundColor = color;
    [self addSubview:image];
    return image;
}

-(void)panGes:(UIPanGestureRecognizer*)panGes{
    //当前点
    CGPoint location = [panGes locationInView:self];
    if (panGes.state == UIGestureRecognizerStateBegan) {
        //告诉上一层开始拖动
        if (self.statusBlcok) {
            self.statusBlcok(kProgressStatusDrag);
        }
    }else if(panGes.state ==UIGestureRecognizerStateChanged){
        //开始滑动
        [self seekToPoint:location.x];
    }else if (panGes.state ==UIGestureRecognizerStateCancelled){
        if (self.statusBlcok) {
            self.statusBlcok(kProgressStatusNormal);
        }
    }
    
    
}

-(void)seekToPoint:(CGFloat)current{
    
    if (! (current<0 || current > self.frame.size.width)) {
        if (self.statusBlcok) {
            self.statusBlcok(kProgressStatusDrag);
        }
        
        //更改前景视图的宽度
        _tintView.frame = CGRectMake(0, 0,current, _tintView.frame.size.height);
        //更改圆点的中心点;
        _dotView.center = CGPointMake(_tintView.frame.size.width, _tintView.frame.size.height/2.0);
        
        //回调数据
        CGFloat progress = current / self.frame.size.width;
        if (self.progressChangeBlock) {
            self.progressChangeBlock(progress);
        }
    }
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    [self seekToPoint:location.x];
}

- (void)setProgress:(CGFloat)progress{
    _progress = progress;
    //更改前景视图的宽度
    _tintView.frame = CGRectMake(0, 0,self.frame.size.width*progress, _tintView.frame.size.height);
    //更改圆点的中心点;
    _dotView.center = CGPointMake(_tintView.frame.size.width, _tintView.frame.size.height/2.0);
    
    NSLog(@"%f",_tintView.frame.size.width);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值