iOS - 如何获得AVPlayer的可播放持续时间

Mys*_*Mac 8 xcode mpmovieplayer ios avplayer

MPMoviePlayerController有一个名为playableDuration的属性.

playableDuration当前可播放内容的数量(只读).

@property(nonatomic,readonly)NSTimeInterval playableDuration

对于逐步下载的网络内容,此属性反映了现在可以播放的内容量.

AVPlayer有类似的东西吗?我在Apple Docs或Google中找不到任何内容(甚至不在Stackoverflow.com)

提前致谢.

小智 16

playableDuration可以通过以下过程大致实现:

- (NSTimeInterval) playableDuration
{
//  use loadedTimeRanges to compute playableDuration.
AVPlayerItem * item = _moviePlayer.currentItem;

if (item.status == AVPlayerItemStatusReadyToPlay) {
    NSArray * timeRangeArray = item.loadedTimeRanges;

    CMTimeRange aTimeRange = [[timeRangeArray objectAtIndex:0] CMTimeRangeValue];

    double startTime = CMTimeGetSeconds(aTimeRange.start);
    double loadedDuration = CMTimeGetSeconds(aTimeRange.duration);

    // FIXME: shoule we sum up all sections to have a total playable duration,
    // or we just use first section as whole?

    NSLog(@"get time range, its start is %f seconds, its duration is %f seconds.", startTime, loadedDuration);


    return (NSTimeInterval)(startTime + loadedDuration);
}
else
{
    return(CMTimeGetSeconds(kCMTimeInvalid));
}
}
Run Code Online (Sandbox Code Playgroud)

_moviePlayer是您的AVPlayer实例,通过检查AVPlayerItem的loadedTimeRanges,您可以计算估计的playableDuration.

对于只有1秒的视频,您可以使用此程序; 但对于多节视频,您可能需要检查loadedTimeRagnes数组中的所有时间范围以获得正确的答案.


Sye*_*man 6

所有你需要的是

self.player.currentItem.asset.duration
Run Code Online (Sandbox Code Playgroud)

最好的