有些人这样做是因为iOS存在漏洞(包括在iOS 12.1.4中),有时会导致AVPlayerItem.duration的值为NaN,即使状态为readyToPlay。例如
这里和
这里。
然而,我的经验是在automaticallyLoadedAssetKeys中指定“duration”并不能解决这个问题 - 尽管苹果的文档
AVPlayerItem中如此写道:
"The value of each key in automaticallyLoadedAssetKeys will automatically be loaded by the underlying AVAsset before the player item achieves the status AVPlayerItem.Status.readyToPlay; i.e. when the item is ready to play, the value returned by invoking the asset property’s statusOfValue(forKey:error:) method will be one of the terminal status values"
我可以得到AVPlayerItem.Status.readyToPlay,statusOfValue(forKey: "duration")返回.loaded,但持续时间为NaN。
我找到的唯一解决方案是KVO AVPlayerItem.status(用于.readyToPlay)和AVPlayerItem.duration(用于有效数字),当任何一个触发时,检查两者。
if item.status != AVPlayerItem.Status.readyToPlay || !item.duration.isUsableNumber() {
return // not ready yet (for addBoundaryTimeObserver, seek to end, etc.)
}
Where isUsableNunber() is just:
func isUsableNumber() -> Bool {
return isValid && isNumeric && !isIndefinite && !isNegativeInfinity && !isPositiveInfinity
}