iOS - How can i get the playable duration of AVPlayer

MystyxMac picture MystyxMac · Jul 25, 2011 · Viewed 18.6k times · Source

The MPMoviePlayerController has a property called playableDuration.

playableDuration The amount of currently playable content (read-only).

@property (nonatomic, readonly) NSTimeInterval playableDuration

For progressively downloaded network content, this property reflects the amount of content that can be played now.

Is there something similar for AVPlayer? I can't find anything in the Apple Docs or Google (not even here at Stackoverflow.com)

Thanks in advance.

Answer

John Lingburg picture John Lingburg · Sep 4, 2012

playableDuration can be roughly implemented by following procedure:

- (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));
}
}

_moviePlayer is your AVPlayer instance, by checking AVPlayerItem's loadedTimeRanges, you can compute a estimated playableDuration.

For videos that has only 1 secion, you can use this procedure; but for multi-section video, you may want to check all time ranges in array of loadedTimeRagnes to get correct answer.