3

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

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))

4

2 回答 2

4

CMTimeGetSeconds文档中:

如果 CMTime 无效或不确定,则返回 NaN。如果 CMTime 是无限的,则返回 +/- 无限。

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

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

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
}
于 2018-11-30T05:24:58.903 回答
1

下面的代码应该可以工作......基本上它发生是因为返回的值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
    }
于 2018-11-30T05:17:15.987 回答