iOS AVAsset.duration is zero for HTTP live streaming but works for progressive

心不动则不痛 提交于 2019-12-05 15:23:09

问题


I have an iOS app that plays video from a HTTP Live stream "playlist.m3u8" and I have a custom player created using AVPlayer. To handle normal user interactions such as scrubbing i need to get the duration of the video, but for some reason on iOS 4.3 using xcode 4.0 when I call the following code I get a CMTime that when converted to seconds gives a NaN -- I know what it's doing because CMTimeValue = 0 and CMTimeScale = 0 which gives the NaN and the CMTimeFlags = 17 which is even more strange.

Here's the code I uses which isn't complex at all:

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

I should also mention that I do monitor the status of the loading playlist to make sure it's ready before i start playing/scrubbing:

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

Thanks for any help on this issues anyone could provide.


回答1:


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.



来源:https://stackoverflow.com/questions/5952694/ios-avasset-duration-is-zero-for-http-live-streaming-but-works-for-progressive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!