AVPlayer自定义视频

// 1. CustomPlayerView.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

/**
 * 1. 创建视图对象
 * 2. 不能将AVPlayer直接添加到视图上,需要添加到自定义的AVPlayerLayer上.
 */

@interface CustomPlayerView : UIView

/** AVPlayer */
@property (nonatomic, strong) AVPlayer *player;

@end


// 2. CustomPlayerView.m
#import "CustomPlayerView.h"

@implementation CustomPlayerView

/*
 * 改变当前层为AVPlayerLayer 这个方法必须重写并返回AVPlayerLayer 自定义AVPlayer需要加在层上才能显示
 */
+ (Class)layerClass {
    return [AVPlayerLayer class];
}

- (void)setPlayer:(AVPlayer *)player {
    _player = player;
    AVPlayerLayer *layer = (AVPlayerLayer *)[self layer];
    // 安装播放器
    layer.player = player;
}
@end

// ViewController.m
#import "ViewController.h"
// 导入头文件
#import <AVFoundation/AVFoundation.h>
#import "CustomPlayerView.h"

@interface ViewController () {
    /**
     *  保存视频的详细信息 (总时间 当前时间 视频状态)
     */
    AVPlayerItem *_playerItem;
}

/**
 *  视频总秒数
 */
@property (nonatomic, assign) NSInteger totalSeconds;
// 进度条
@property (weak, nonatomic) IBOutlet UISlider *slider;
// 当前时间标签
@property (weak, nonatomic) IBOutlet UILabel *currentLabel;
// 总时间标签
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
// 视频播放器 可以播放本地视频 也可以播放远程视频
@property (nonatomic, strong) AVPlayer *avPlayer;
// 自定义播放视图
@property (nonatomic, weak) CustomPlayerView *playerView;

- (IBAction)slider:(UISlider *)sender;
- (IBAction)playOrPauseAction:(UIButton *)sender;

@end

@implementation ViewController

/**
 *  playerView
 */
- (CustomPlayerView *)playerView {
    if (_playerView == nil) {
        CustomPlayerView *playerView = [[CustomPlayerView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)];
        // 给playerView一个AVPlayer
        playerView.player = self.avPlayer;
        [self.view addSubview:playerView];
        _playerView = playerView;
    }
    return _playerView;
}

/**
 *  AVPlayer
 */
- (AVPlayer *)avPlayer {
    if (_avPlayer == nil) {
        // 这个url既可以是本地也可以是远程的。
        _playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:@"http://121.40.54.242:280/zhangchu/video/hotwater/fulingbaihekaiweitang.mp4"]];
        _avPlayer = [[AVPlayer alloc] initWithPlayerItem:_playerItem];
    }
    return _avPlayer;
}


- (IBAction)playOrPauseAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.avPlayer play];
    } else {
        [self.avPlayer pause];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // AVPlayer 只能放到层上(AVPlayerLayer)才能够进行播放  放到视图上不能正常播放
    // 改变当前视图的层
    [self playerView];
    
    /* KVO来监听AVPlayerItem的状态
     [A addObserver:B forKeyPath:@"属性C"];
     当A的属性值发生变化后,调用B的observeValueForKeyPath:
     */
    
    // 观察当前播放器的状态 _playerItem中的状态值
    [_playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    // 状态值发生变化
    if ([keyPath isEqualToString:@"status"]) {
        NSString *new = change[NSKeyValueChangeNewKey];
        if ([new integerValue] == AVPlayerItemStatusReadyToPlay) {
            
            /** 思路:
             *   1. 得到总时长显示出来 AVPlayerItem.duration 和 CMTimeGetSeconds
             *   2. 当前时间需要不断更新,所以AVPlayer有一个代码块方法可以做到
             */
            // 获取总时间
            // 注意 一定要在视频的status状态为AVPlayerItemStatusReadyToPlay才能获取到总时间
            
            // CoreMedia
            CMTime time =  _playerItem.duration;
            // 从CMTime对象转化为秒
            _totalSeconds = CMTimeGetSeconds(time); // 总帧数/帧率
            // 更新界面
            self.totalLabel.text = [self stringFormatterWithSecond:_totalSeconds];
            
            //   CMTimeMake(@"当前帧", @"帧率");
            //   time.value / time.timescale;
            //   Periodic 周期
            /**
             *  循环引用的原因
             1. self.avPlayer调用这个block块说明self持有了这个block块
             2. block又持有了self的全局变量_weakItem等所有需要将self和Item设置为weak,避免循环引用。
             
             */
            // 更新当前时间 多久更新一次
            __weak AVPlayerItem   *_weakItem = _playerItem;
            __weak ViewController *_weakSelf = self;
            [self.avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
                
                // 获取当前时间
                CMTime currentTime = _weakItem.currentTime;
                // 当前时间转化为秒
                NSInteger second = CMTimeGetSeconds(currentTime);
                
                _weakSelf.slider.value = (float)second/_weakSelf.totalSeconds;
                _weakSelf.currentLabel.text = [_weakSelf stringFormatterWithSecond:second];
            }];
        }
    }
}

/**
 *   把second转化为hh:mm:ss格式的
 */
- (NSString *)stringFormatterWithSecond:(NSInteger)second {
    int hour = (int)second / 3600;
    int minute = (int)(second-hour*3600)/60;
    int sec = (int)second % 60;
    return [NSString stringWithFormat:@"%02d:%02d:%02d",hour,minute,sec];
}

/**
 *  通过滑动slider来跳到指定帧 从而达到快放和回看的功能
 */
- (IBAction)slider:(UISlider *)sender {
    // 1. 计算帧
    //  01 - 帧率 * 当前时长 = 帧
    CMTime time = _playerItem.currentTime;
    time.value =  _playerItem.currentTime.timescale * (_totalSeconds * sender.value);
    // 2. 跳到指定帧
    [self.avPlayer seekToTime:time];
}

- (void)dealloc {
    [_playerItem removeObserver:self forKeyPath:@"status"];
}

@end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值