[英]Converting CMTime To String is wrong value return
I want CMTime
to String an human readable. 我希望CMTime
能够将人类可读。
So I Found below code. 所以我发现下面的代码。
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)
}
}
}
And I Have 30 second
video files. 我有30 second
视频文件。 It's CMTime
value is 17945
. 这是CMTime
值是17945
。
I expect this durationText 00:30
. 我希望这个durationText 00:30
。
But result is 00:29
. 但结果是00:29
。
And other video files same. 和其他视频文件一样。
What Should I fix?? 我该怎么办?
You need to round your seconds before calculating your time components. 在计算时间分量之前,您需要计算几秒钟。
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)
}
}
Testing all the possible edge rounding cases: 测试所有可能的边缘舍入情况:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.