Receiving Fatal error: Double value cannot be converted to Int because it is either infinite or NaN

Receiving Fatal error: Double value cannot be converted to Int because it is either infinite or NaN

该代码用于播客应用程序。

import AVKit

extension CMTime {
func toDisplayString() -> String {
    let totalSeconds = Int(CMTimeGetSeconds(self))
    let seconds = totalSeconds % 60
    let minutes = totalSeconds / 60
    let timeFormatString = String(format: "%02d:%02d", minutes, seconds)
    return timeFormatString
}
}

选择要播放的播客时失败...导致音频播放但应用程序冻结,直到重新启动。

编辑:错误发生在行 let totalSeconds = Int(CMTimeGetSeconds(self))

下面的代码应该可以工作...基本上它发生是因为 CMTimeGetSeconds(self) 返回的值超出了 Int 限制。

func toDisplayString() -> String {
        let totalSeconds:TimeInterval = TimeInterval(CMTimeGetSeconds(self))
        let seconds:TimeInterval = totalSeconds.truncatingRemainder(dividingBy: 60)
        let minutes:TimeInterval = totalSeconds / 60
        let timeFormatString = String(format: "%02d:%02d", minutes, seconds)
        return timeFormatString
    }

来自CMTimeGetSeconds documentation

If the CMTime is invalid or indefinite, NaN is returned. If the CMTime is infinite, +/- infinity is returned.

CMTimeGetSeconds return 为 NaN 或无穷大时,将 return 值转换为 Int 将抛出您所看到的致命错误。

您可以先检查该值,然后 return 某种默认值以防它不是有效数字。

func toDisplayString() -> String {
    let rawSeconds = CMTimeGetSeconds(self)
    guard !(rawSeconds.isNaN || rawSeconds.isInfinite) else {
       return "--" // or some other default string
    }
    let totalSeconds = Int(rawSeconds)
    let seconds = totalSeconds % 60
    let minutes = totalSeconds / 60
    let timeFormatString = String(format: "%02d:%02d", minutes, seconds)
    return timeFormatString
}