0

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
    })
KamaroY
  • 35
  • 5
  • 1
    DispatchQueue deadlines are no where near reliable enough to deal with metronome functionality, unfortunately. If you're dealing with AudioKit already you could look into sequencing a specific pattern and playing that, where you could guarantee that the sequence would be in-sync relative to itself when the tempo changes. – jnpdx Mar 18 '21 at 01:38
  • @jnpdx Thanks. I will check how to program the sequencer. – KamaroY Mar 19 '21 at 01:08
  • @jnpdx could you kindly give me an example on how to program a presetted sequence using AudioKit? Such as using AudioKit Cookbook's example ( https://github.com/AudioKit/Cookbook/blob/main/Cookbook/Cookbook/Recipes/Shaker.swift) to show how to program the sequence I mentioned above? Thank you – KamaroY Mar 19 '21 at 01:25
  • Sorry, I'm not super familiar with that element of AudioKit, so I'd be doing research, just like you. The cookbook is a great resource, though -- keep digging through that and experimenting. – jnpdx Mar 19 '21 at 02:44

0 Answers0