Swift CMTime
When you operate time it is important to save accuracy. CMTime
propose you to use two integers(value and timescale) to present a float number. Additional functions simplify CMTime mathematics in contrast to float operations
Important CMTime
properties are:
- value
- timescale - number of equal parts of one second
- seconds
The formula is
Int64 value(numerator) / Int32 timescale(denominator) = Float64 seconds
//for example
//value 1 / timescale 10 = 1/10(0.1) seconds
Next example shows next items:
- You can create CMTime using constructor(init()) or CMTimeMake function
- time.seconds is the same as CMTimeGetSeconds(time)
- mathematics with CMTime - CMTimeCompare, CMTimeAdd...
import CoreMedia
func testTime() {
let value: Int64 = 1
let timescale: Int32 = 10
let secondsResult: Double = 0.1 // 1/10 sec
let time1: CMTime = CMTime(value: value, timescale: timescale)
let time2: CMTime = CMTime(seconds: secondsResult, preferredTimescale: timescale)
let time3: CMTime = CMTimeMake(value: value, timescale: timescale)
let time4: CMTime = CMTimeMakeWithSeconds(secondsResult, preferredTimescale: timescale)
let seconds1: Double = time1.seconds
let seconds2: Float64 = CMTimeGetSeconds(time1)
assert(seconds1 == seconds2)
assert(seconds1 == secondsResult)
assert(time1 == time2)
assert(time1 == time3)
assert(time1 == time4)
assert(CMTimeCompare(time1, time2) == 0)
}
Create CMTime using seconds
You are able to create CMTime
using value and timescale where seconds will be calculated(value / timescale). This approach is clear but also you are able to create CMTime
using seconds and preferredTimescale. In this case your value and seconds can be different and be recalculated to satisfy formula(value must be Int64) that is why it can be rounded, as a result seconds also is recalculated
//preset - seconds: 0.1, preferredTimescale: 10, expect value == 1
//result - seconds: 0.1, value: 1
let time5: CMTime = CMTime(seconds: 0.1, preferredTimescale: 10)
assert(time5.value == 1)
assert(time5.seconds == 0.1)
//preset - seconds: 0.1, preferredTimescale: 1, expect value == 0.1
//result - seconds: 0, value: 0
let time6: CMTime = CMTime(seconds: 0.1, preferredTimescale: 1)
assert(time6.value == 0)
assert(time6.seconds == 0)
//preset - seconds: 1.31, preferredTimescale: 10, expect value == 13.1
//result - seconds: 1.3, value: 13
let time7: CMTime = CMTime(seconds: 1.31, preferredTimescale: 10)
assert(time7.value == 13)
assert(time7.seconds == 1.3)
CMTimeMake(1, 48)
to run a block of code every 1/48 of a second ie 1 block per frame – Irrationality