美文网首页iOS学霸笔记
iOS 视频播放的那点事

iOS 视频播放的那点事

作者: 忘川_之上 | 来源:发表于2016-10-21 16:06 被阅读60次

    AVPlayer视频播放

    1、初始化AVPlayer

    + (instancetype)playerWithURL:(NSURL *)URL;

    + (instancetype)playerWithPlayerItem:(AVPlayerItem *)item;

    - (instancetype)initWithURL:(NSURL *)URL;

    - (instancetype)initWithPlayerItem:(AVPlayerItem *)item;

    媒体资源管理对象AVPlayerItem,每个AVPlayerItem对应一个视频资源

    NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.161/%i.mp4",videoIndex];

    urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURL *url=[NSURL URLWithString:urlStr];

    AVPlayerItem *playerItem=[AVPlayerItem playerItemWithURL:url];

    使用AVPlayerLayer展示AVPlayer:控制AVPlayerLayer来完成全屏等操作

    AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:self.player];

    [self.view.layer addSublayer:playerLayer];

    2、播放暂停方法

    - (void)play;

    - (void)pause;

    通过属性rate了解播放状态

    如果rate为0说明是停止状态,1为正常状态 ;

    设置rate为0.0等同于pause方法,改为1.0等同于pause方法,所以很多时候我们是通过判断rate == 0.0 来获取实际的播放状态

    通过属性status了解播放状态

    AVPlayerStatusUnknown,

    AVPlayerStatusReadyToPlay,

    AVPlayerStatusFailed

    3、获得播放进度方法addPeriodicTimeObserverForInterval

    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {

    float current=CMTimeGetSeconds(time);

    float total=CMTimeGetSeconds([playerItem duration]);

    NSLog(@"当前已经播放%.2fs.",current);

    NSLog(@" 播放进度%.2fs.",current/total);

    4、为AVPlayerItem添加视频播放完成通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];

    5、为AVPlayerItem添加KVO来处理视频播放时候的变化

    添加kvo事件

    6、处理键值观察事件,当然最后要记得将观察者移除

    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    AVPlayerItem *playerItem=object;

    if ([keyPath isEqualToString:@"status"]) {

    AVPlayerStatus status= [[change objectForKey:@"new"] intValue];

    if(status==AVPlayerStatusReadyToPlay){

    NSLog(@"正在播放...,视频总长度:%.2f",CMTimeGetSeconds(playerItem.duration));

    }

    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){

    NSArray *array=playerItem.loadedTimeRanges;

    CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围

    float startSeconds = CMTimeGetSeconds(timeRange.start);

    float durationSeconds = CMTimeGetSeconds(timeRange.duration);

    NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度

    NSLog(@"共缓冲:%.2f",totalBuffer);

    }

    }


    相关文章

      网友评论

      本文标题: iOS 视频播放的那点事

      本文链接:https://www.haomeiwen.com/subject/pijfuttx.html