Hello. I just started working on a metronome app that I would like to create. I’m having trouble with triggering the beat on precise time intervals. Besides that, Processing’s graphics are inconsistent too.
The logic is simple. I want to have a metronome running at 120 beats per minute, which precisely translates to 1 beat per 500,000,000 nanoseconds. What I’ve tried to do is store the system timer during time of initialisation, then increment that by 500,000,000 and trigger a tick every time the system time equals that incremented time.
For simplicity’s sake, I have replaced the tick with a print statement that prints out ‘Boom{n}’ for the nth tick since initialisation.
The problem: There is a significant lag between the time that it is suppose to trigger and the time that it actually does. This can be seen through the print statements (I used long variables to calculate this). On average, the gap between two ticks was ~530,000,000 which is almost a 0.03 seconds lag per tick. Over time, this lag accumulates and the accuracy is unacceptable for a metronome.
Here’s the code:
long initSysTime;
int c = 0;
float bpm = 120;
float interval = 1e9 / (bpm / 60);
float nextTime;
void setup() {
size(600, 600);
//frameRate(120);
initSysTime = System.nanoTime();
nextTime = initSysTime + interval;
}
void draw() {
background(0);
float temp = System.nanoTime();
//ellipse(width/2, height/2, height/2, height/2);
// This isn't being drawn while testing to better see the ellipses that Processing doesn't draw when triggered, despite the trigger going off, as seen through the print statements in the if statement
if(temp == nextTime) {
nextTime = temp + interval;
ellipse(width/2, height/2, height/2 + 0.016*height, height/2 + 0.016*height);
c++;
println("Boom" + c);
println("SysTime = " + temp);
}
}
I had a look at this topic too: Issues creating a metronome
The best suggestion redirected me to a countdown library (https://github.com/dhchoi/processing-countdowntimer), whose source code I looked into and over here too, System.nanoTime()
was used for precision.
Any help is sincerely appreciated. Thank you for taking the time to read this.