x bpm = x beats per minute = x/60 beats per second
So the time between two beats (period in seconds) is:
p = 60/x
You see that at 60 bpm:p = 60/60 = 1 second
. At 120bpm, p = 60/120 = 0.5 second
.
I also started programming a metronome (in GTK+ on Linux, but should work on Windows too if you install GTK+ separately), and things can get tricky in the timing. The problem is that you can't rely on the fact that your timers will wake you on the exact moment they should, unless you use a real-time operating system.
So there's a risk you play your tick slightly after the moment you wanted. The problem is that if you just measure the interval between two ticks, you miss the problem: errors add up at each tick, and after some tens of seconds, you are completely out of sync.
To avoid that, what I do is:
- get current time at the moment the metronome is fired up
- calculate the time of the next tick (tick 1)
- set a timer to call me back when it's time to play tick 1, and "sleep" for that duration
- when waking up, get the current time and play the tick sound for tick 1
- calculate the time of tick 2, not based on current time but on the theoretical time tick 1 was supposed to be played
- calculate the difference between the current time and the time tick 2 is supposed to be played, and "sleep" for that duration
- etc.
This way if there's some lag at some point, you won't be completely out-of-sync at the end of the song. This allows for example to change the BPM while the ticks are played while still remaining reactive.
My code (in C) is at:
https://github.com/liberforce/metrognome