首页 文章

如何知道AVPlayerItem何时被缓冲到歌曲的结尾

提问于
浏览
1

我正在尝试确定判断AVPlayerItem是否缓冲到流末尾的最佳方法 . 不仅缓冲区已满,而且缓冲区包含播放项目其余部分所需的所有内容,无需额外的缓冲 . AVPlayerItem提供了一个isPlaybackBufferFull调用,但这并没有告诉我在项目完成播放之前是否需要进行任何额外的缓冲 .

我目前的计划是将它与preferredForwardBufferDuration结合起来检查项目是否需要缓冲更多,但这是最好的方法吗?

例如:

- (void)observeValueForKeyPath:(NSString*)aKeyPath ofObject:(id)aObject change:(NSDictionary*)aChange context:(void*)aContext
{
    if( [aKeyPath isEqualToString:@"playbackBufferFull"] )
    {
        CMTime theBufferTime = CMTimeMakeWithSeconds( self.currentItem.preferredForwardBufferDuration, 1 );
        CMTime theEndBufferTime = CMTimeAdd( self.currentItem.currentTime, theBufferTime );
        if( CMTimeCompare( theEndBufferTime, self.currentItem.duration ) >= 0 )
        {
            // Buffered to the end
        }
    }
}

1 回答

  • 0

    我找到了一个很好的解决方案,可以在下面看到这个问题 . 在问题中编写的建议解决方案并没有真正起作用,因为preferredForwardBufferDuration默认设置为0,这几乎使解决方案不可行 .

    以下代码非常有效 . 我在计时器上每秒都叫它 .

    auto theLoadedRanges = self.currentItem.loadedTimeRanges;
    
    CMTime theTotalBufferedDuration = kCMTimeZero;
    for( NSValue* theRangeValue in theLoadedRanges )
    {
        auto theRange = [theRangeValue CMTimeRangeValue];
        theTotalBufferedDuration = CMTimeAdd( theTotalBufferedDuration, theRange.duration );
    }
    
    auto theDuration = CMTimeGetSeconds( self.currentItem.duration );
    if( theDuration > 0 )
    {
        float thePercent = CMTimeGetSeconds( theTotalBufferedDuration ) / theDuration;
        if( thePercent >= 0.99f )
        {
            // Fully buffered
        }
    }
    

相关问题