Swift 将CMTime转换为字符串返回的值错误

Swift 将CMTime转换为字符串返回的值错误,swift,string,cmtime,Swift,String,Cmtime,我希望CMTime为人类可读的字符串设置字符串。 所以我找到了下面的代码 extension CMTime { var durationText:String { let totalSeconds = CMTimeGetSeconds(self) let hours:Int = Int(totalSeconds / 3600) let minutes:Int = Int(totalSeconds.truncatingRemainder(d

我希望
CMTime
为人类可读的字符串设置字符串。
所以我找到了下面的代码

extension CMTime {

    var durationText:String {
        let totalSeconds = CMTimeGetSeconds(self)
        let hours:Int = Int(totalSeconds / 3600)
        let minutes:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60)
        let seconds:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 60))

        if hours > 0 {
            return String(format: "%i:%02i:%02i", hours, minutes, seconds)
        } else {
            return String(format: "%02i:%02i", minutes, seconds)
        }
    }

}
我有30秒的视频文件。它是
CMTime
值是
17945

我希望这段时间text
00:30

但结果是
00:29

和其他视频文件相同。

我应该修正什么???

在计算时间分量之前,您需要将秒舍入

extension CMTime {
    var roundedSeconds: TimeInterval {
        return seconds.rounded()
    }
    var hours:  Int { return Int(roundedSeconds / 3600) }
    var minute: Int { return Int(roundedSeconds.truncatingRemainder(dividingBy: 3600) / 60) }
    var second: Int { return Int(roundedSeconds.truncatingRemainder(dividingBy: 60)) }
    var positionalTime: String {
        return hours > 0 ?
            String(format: "%d:%02d:%02d",
                   hours, minute, second) :
            String(format: "%02d:%02d",
                   minute, second)
    }
}

测试所有可能的边缘圆角情况:

CMTime(value: 0, timescale: 600).positionalTime              // "00:00"
CMTime(value: 300, timescale: 600).positionalTime            // "00:01"
CMTime(value: 600, timescale: 600).positionalTime            // "00:01"

CMTime(value: 18000 - 600, timescale: 600).positionalTime      // "00:29"
CMTime(value: 17945, timescale: 600).positionalTime            // "00:30"
CMTime(value: 18000, timescale: 600).positionalTime            // "00:30"
CMTime(value: 18055, timescale: 600).positionalTime            // "00:30"
CMTime(value: 18000 + 600, timescale: 600).positionalTime      // "00:31"


CMTime(value: 2160000 - 600, timescale: 600).positionalTime  // "59:59"
CMTime(value: 2160000 - 300, timescale: 600).positionalTime  // "1:00:00"
CMTime(value: 2160000, timescale: 600).positionalTime        // "1:00:00"

您的durationText扩展为我返回
00:30
。当我运行
CMTime(值:30,时间刻度:1)时。durationText
您的视频持续时间小于30秒。持续时间为
29.90833333
?如果你需要的话,自己把结果汇总起来
seconds.rounded(.up)
最好使用标准的
rounded()
,它使用
.toNearestOrAwayFromZero
舍入规则。@LeoDabus非常感谢。我修好了。你什么都可以回答。我选择你的答案。