Swift: how to calculate the correct dispatch time in a metronome

292 Views Asked by At

I am developing a metronome in my App and I want to implement a feature where the metronome can change its tempo at a certain time. For example, plays 4 ticks at a tempo = 120 bpm and then plays 8 ticks at a tempo = 200 bpm and then go back to 120 bpm.

I try this by using the AKMetronome from AudioKit and update the tempo using DispatchQueue.main.asyncAfter. However, the tempo is kinda off and have noticeable lag. Is the calculation wrong or am I missing something?

    metronome.tempo = 120
    let first_interval = 60.0 / 120.0
    let switchTime1 = DispatchTime.now() + (first_interval * 4.0)
    metronome.play()
    
    DispatchQueue.main.asyncAfter(deadline: switchTime1, execute: {
        self.metronome.tempo = 200
    })
    
    let second_inter = 60.0 / 200.0
    let switchTime2 = switchTime1 + (second_inter * 8.0)
    
    DispatchQueue.main.asyncAfter(deadline: switchTime2, execute: {
        self.metronome.tempo = 120
    })
0

There are 0 best solutions below