AVPlayer 获取时间问题

作者: 幕夜丶席 | 来源:发表于2016-12-15 14:13 被阅读3056次

使用 AVPlayer 获取播放的时间和播放的总时间,在使用的时候踩到一些坑在这总结一下

获取已经播放的时间

CMTime time = self.player.currentTime;

NSTimeIntval currentTimeSec = time.value / time.timesacle;

获取总时间 3中方法

// 1. 直接通过 player的 duration 获取总时间
// 1.1
CMTime time = self.player.currentItem.duration;
Float64 seconds = CMTimeGetSeconds(time);
// 1.2 也可以通过 asset 获取duration 然后转floa64
CMTime time = self.player.currentItem.asset.duration;
Float64 seconds = CMTimeGetSeconds(time);

// 2.通过添加 addPeriodicTimeObserverForInterval 通知获取 注意:需要移除这个通知
id observer =[self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(2, 1) queue:nil usingBlock:^(CMTime time){   
    AVPlayerItem* currentItem = self.player.currentItem;  
    NSArray* loadedRanges = currentItem.seekableTimeRanges;  
    if (loadedRanges.count > 0)  
    {  
        CMTimeRange range = [[loadedRanges objectAtIndex:0] CMTimeRangeValue];  
        Float64 duration = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration);  
        // 当前播放总时间
        NSLog(@"duration:%g", duration);  
    }  
}];

// 3.通过KVO 监听 获取 同时也需要移除Observer
    [self.playItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.playItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    //判断链接状态
    if ([keyPath isEqualToString:@"status"]) {
        if (self.playItem.status == AVPlayerItemStatusFailed) {
            NSLog(@"连接失败");
        }else if (self.playItem.status == AVPlayerItemStatusUnknown){
            NSLog(@"未知的错误");
        }else{
            NSLog(@"准备播放");
          self.AllTime = CMTimeGetSeconds(self.playItem.duration);
        }
    }
}


// 之前写的现在过来修改下 ,其实第3中方法就能获取到总时间正确的顺序应该这样
- (void)playWithURL:(NSURL *)url {
    AVURLAsset *asset = [AVURLAsset assetWithURL:url];
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    self.player = [AVPlayer playerWithPlayerItem:item];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey] integerValue];
        if (status == AVPlayerItemStatusReadyToPlay) {
            NSLog(@"AVPlayerItemStatusReadyToPlay");
            [self.player play];
        } else if (status == AVPlayerItemStatusUnknown) {
            NSLog(@"AVPlayerItemStatusUnknown");
        } else if (status == AVPlayerItemStatusFailed) {
            NSLog(@"AVPlayerItemStatusFailed");
        }
    }
}

// 获取总时间,但是刚开始有可能是Nan,判断下就ok了
// 这个总时间在外面设置的时候基本都是一起刷新UI显示的所以设置个Timer更新显示就行了
- (NSTimeInterval)totalTime {
    CMTime totalTime = self.player.currentItem.duration;
    NSTimeInterval sec = CMTimeGetSeconds(totalTime);
    if (isnan(sec)) {
        return 0;
    }
    return sec;
}
// 其他的数据AVPlayer 其实都有提供,比如说加载,缓存进度
- (float)loadDataProgress {
    if (self.totalTime == 0) {
        return 0;
    }
    CMTimeRange range = [[self.player.currentItem loadedTimeRanges].lastObject CMTimeRangeValue];
    CMTime loadTime = CMTimeAdd(range.start, range.duration);
    return CMTimeGetSeconds(loadTime) / self.totalTime;
}

主要是在获取总时间的时候一直获取不到,通过方法1,方法3总是获取不到时间,currentItem总是返回的duration 结构体一直是空的 转成float后一直是NaN,可能是我的链接有问题,最后使用方法2 才获取到了正确的总时间,

相关文章

网友评论

  • holybin:之所以为NaN是因为duration 还不可用,要等到AVPlayerItem 的status为AVPlayerItemStatusReadyToPlay 才可以正确获取到,这也就是为什么第三种方式可以一次性获取准确的原因。
    参考:https://stackoverflow.com/questions/23874574/avplayer-item-get-a-nan-duration
  • LD_左岸:楼主没试试这种方法直接拿总时长吗
    Float64 totalSec = CMTimeGetSeconds(currentItem.asset.duration);
    幕夜丶席:可以试试,但是前提是通过 AVURLAsset 创建的才行
  • LD_左岸:(lldb) po currentItem
    <AVPlayerItem: 0x60c0000196e0, asset = <AVURLAsset: 0x60c000223700, URL = http://120.25.226.186:32812/resources/videos/minion_03.mp4>;>

    (lldb) po currentItem.seekableTimeRanges
    <__NSArray0 0x6040000170a0>(

    )

    (lldb)
  • 猫猫_a011:我必须要说一下,通过方法二获取的时间有一定的概率是不准确的,总是会比item.duration长或者短若干秒 :sob: :sob: :sob:
    幕夜丶席:@要学很多东西 啪,捂脸,好久没来改,够来修改了一下,第3中方法改了改,第2种方法是一点一点获取的,第3中是直接获取总时间的
    买了否冷_:请教 那怎么获取正确总时长和已播放时长呢

本文标题:AVPlayer 获取时间问题

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