使用 AVFoundation 获取视频的持续时间

Get duration of video with AVFoundation

要获得 AVPlayerItem 的持续时间,我可以这样做:player.currentItem.duration

除此之外,我还可以从后端获取持续时间作为 Int。然后我可以将其转换为 Float 以便在需要持续时间的任何地方使用。我认为这在性能方面可能会更好,并且在我这边获得持续时间的工作更少。

例如 Apple 是这样描述获取时长的:

“A vital concept in AV Foundation is that initializing an asset or a track does not necessarily mean that it is ready for use. It may require some time to calculate even the duration of an item (an MP3 file, for example, may not contain summary information). Rather than blocking the current thread while a value is being calculated, you ask for values and get an answer back asynchronously through a callback that you define using a block.”

如果我决定通过从服务器获取持续时间来对持续时间进行硬编码,有什么可能出错的想法吗?这是好的做法吗?

如果您已经知道后端的值,并且已经打电话说要获取视频 URL,那么检索持续时间似乎是一个合理的想法。

尽管 - 是否有可能不匹配?如果您在客户端执行此操作,则 "guaranteed" 是正确的。

如果你必须打一个特殊的电话来获取它,我不会,因为它可能比在资产初始化期间确定它花费更长的时间。