10

我有一个 iOS 应用程序可以播放来自 HTTP Live 流“playlist.m3u8”的视频,并且我有一个使用 AVPlayer 创建的自定义播放器。为了处理正常的用户交互,例如擦洗,我需要获取视频的持续时间,但由于某种原因,在 iOS 4.3 上使用 xcode 4.0 调用以下代码时,我得到一个 CMTime,当转换为秒时会给出一个 NaN - 我知道它在做什么,因为 CMTimeValue = 0 和 CMTimeScale = 0 这给出了 NaN 和 CMTimeFlags = 17,这更奇怪。

这是我使用的代码,它一点也不复杂:

AVPlayerItem *pItem = mPlayer.currentItem;
AVAsset* asset = pItem.asset;
CMTime d = asset.duration;
double duration = CMTimeGetSeconds(asset.duration);

我还应该提一下,我确实会监控加载播放列表的状态,以确保在我开始播放/擦洗之前它已准备就绪:

[mPlayer addObserver:self forKeyPath:@"currentItem.status" options:0 context:VideoPlaybackViewDelegateStatusContext];

感谢您在此问题上提供的任何帮助。

4

1 回答 1

8

https://developer.apple.com/library/ios/releasenotes/AudioVideo/RN-AVFoundation-Old/#//apple_ref/doc/uid/TP40011199-CH1-SW4

The docs above mention that duration should now be obtained from the AVPlayerItem instance, rather than its corresponding AVAsset. To get the duration from the current player item via key-value observing, I use the following method (originally pulled from NGMoviePlayer which was written for iOS 4.0):

- (void)loadPlayerWithItem:(AVPlayerItem *)playerItem {
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    ...
    // changed this from previous value currentItem.asset.duration
    [self.player addObserver:self forKeyPath:@"currentItem.duration"
                                     options:0
                                     context:nil];
    ...
}

I implemented the above change in my player and the duration is working now! This change in AVFoundation was the root cause of the issue. CMTimeFlags = 17 indicates kCMTimeFlags_Indefinite & kCMTimeFlags_Valid, and the docs specify:

In particular, the duration reported by the URL asset for streaming-based media is typically kCMTimeIndefinite, while the duration of a corresponding AVPlayerItem may be different and may change while it plays.

于 2011-05-11T00:35:26.473 回答