问题如下:
节奏类游戏需要执行很多的跟音乐节拍相关的操作,并且为了保证节奏感,需要让操作跟节拍的关系十分紧密。对两者间隔要求不能超过0.02秒或更低。
目前使用了 GCD 中的 asyncAfter(deadline:)方法,不过误差总是要大于0.05秒,并且还无法保证误差会不会传递下去。请问有更好的方式来解决误差吗?
var time = Date().timeIntervalSince1970
let dq = DispatchQueue(label: "queue", qos: .userInitiated, attributes: [.concurrent, .initiallyInactive])
dq.async {
self.audioPlayer.play()
time = Date().timeIntervalSince1970
}
dq.asyncAfter(deadline: .now() + 0.43, execute: {
let res = Date().timeIntervalSince1970
print(" 误差: \(res - time)")
})
以下是多次运行控制台打印结果(该数字指的是实际间隔,与期望间隔的0.43相差甚远,且不稳定):
怪我咯2017-04-18 09:58:48
Mention an engineering rather than a technical idea.
When the program starts, it first runs the test for the average delay time, and then still uses the standard time for timing, but uses the difference between the standard time and the average delay time to delay execution.