最近在搞avplayer,HTTP Live Streaming Media.其中测试发现了一个bug,在使用airplay时有时候会出现总时间不正确的情况,大概可能在网络不好的情况下出现,总时间为1秒.
在官方sdk里面的demo里面获取duration的代码:
1 /* --------------------------------------------------------- 2 ** Get the duration for a AVPlayerItem. 3 ** ------------------------------------------------------- */ 4 5 - (CMTime)playerItemDuration 6 { 7 AVPlayerItem *playerItem = [mPlayer currentItem]; 8 if (playerItem.status == AVPlayerItemStatusReadyToPlay) 9 { 10 /* 11 NOTE: 12 Because of the dynamic nature of HTTP Live Streaming Media, the best practice 13 for obtaining the duration of an AVPlayerItem object has changed in iOS 4.3. 14 Prior to iOS 4.3, you would obtain the duration of a player item by fetching 15 the value of the duration property of its associated AVAsset object. However, 16 note that for HTTP Live Streaming Media the duration of a player item during 17 any particular playback session may differ from the duration of its asset. For 18 this reason a new key-value observable duration property has been defined on 19 AVPlayerItem. 20 21 See the AV Foundation Release Notes for iOS 4.3 for more information. 22 */ 23 24 return([playerItem duration]); 25 } 26 27 return(kCMTimeInvalid); 28 }
在注释中有提到在iOS 4.3之前需要通过AVAsset来获取.为了兼容4.3以下的系统,对这里有进行一下修改
1 if ([playerItem respondsToSelector:@selector(duration)]) { 2 return([playerItem duration]); 3 } else if ([playerItem respondsToSelector:@selector(asset)]) { 4 AVAsset *asset = [playerItem asset]; 5 if (asset) { 6 return [asset duration]; 7 } 8 }
后来发现一个问题就是[playerItem duration]有可能不会返回正确的数,而是返回了一个奇怪的数据,通过CMTimeGetSeconds(time)得到的是1秒,而同时[asset duration]返回的却是正确的数据.
这大概可能是AVPlayerItem的一个bug.在改成通过AVAsset获取时间之后就没有再重现出总时间不正确的情况了.
但是毕竟在官方demo里面注释说明有可能这两个值不一样,优先使用哪一个还是具体斟酌再定吧.