我正在尝试制作一个需要非常精确的计时器的音乐应用程序(它需要与背景音乐同步)。我还需要在用户界面上将计时器显示为进度条。
我最初是从NSTimer
,事实证明根本不准确,关闭时间超过 20 毫秒。我转向 GCD。但我似乎也无法让它发挥作用。
这是我的代码(删除了不相关的部分)
这是我的 ViewController 类中的第一行
var dispatchQueue = dispatch_queue_t()
而在我的override func viewDidLoad()
功能
dispatchQueue = dispatch_queue_create("myQueueId", nil)
然后是使用调度队列的实际函数
// Generate new measure
// In the main dispatch queue because it handles a lot of work
func newMeasure() {
timerBar.progress = 1.0
// Reset the timer
logEnd = NSDate()
let lapse = logEnd.timeIntervalSinceDate(logStart)
println("Lapse: \(lapse)")
logStart = NSDate()
// measureTimer is set to 1.47, so the newMeasure is supposedly to be called every 1.47 seconds
timer = measureTimer
startTime = NSDate()
dispatch_async(dispatchQueue, {
self.gameTimer()
})
// ... do a lot of stuff that will drag the timer if not put in dispatch queue
}
// Accurate Game Timer
// In the dispacheQueue so the timer can has its own thread
func gameTimer() {
// Get the time now
let now = NSDate()
let adjust = now.timeIntervalSinceDate(self.startTime)
// Refresh the start time to be now
self.startTime = now
self.timer = self.timer - adjust
// Go back to the main dispatch queue to update UI
dispatch_async(dispatch_get_main_queue(), {
self.timerBar.progress = Float(self.timer / self.measureTimer)
})
if (self.timer <= 0.2) {
dispatch_async(dispatch_get_main_queue(), {
// Going back to the main dispatch queue to start another new measure
NSTimer.scheduledTimerWithTimeInterval(self.timer, target: self, selector: Selector("newMeasure"), userInfo: nil, repeats: false)
})
}
else {
dispatch_after(dispatch_time_t(
100 * NSEC_PER_MSEC), dispatchQueue, {
self.gameTimer()
})
}
}
但实际的日志是这样的:
Lapse: 1.47152501344681
Lapse: 1.51420003175735
Lapse: 1.47065001726151
Lapse: 1.47149801254272
Lapse: 1.471755027771
Lapse: 1.47201299667358
Lapse: 1.47167503833771
Lapse: 1.47148901224136
Lapse: 1.47146201133728
Lapse: 1.47289103269577
Lapse: 1.47580003738403
Lapse: 1.47087097167969
Lapse: 1.47286003828049
Lapse: 1.47235900163651
Lapse: 1.47159999608994
Lapse: 1.47144496440887
Lapse: 1.50616401433945
Lapse: 1.51679295301437
Lapse: 1.47380495071411
Lapse: 1.47130501270294
Lapse: 1.50468301773071
Lapse: 1.4718160033226
Lapse: 1.49480104446411
Lapse: 1.50195497274399
Lapse: 1.50018000602722
Lapse: 1.47339296340942
Lapse: 1.47266495227814
他们仍然不那么准时。因为时间对音乐非常敏感,所以这是行不通的。
有人可以帮我解决这个准确性问题吗?
谢谢