Skip to content

Instantly share code, notes, and snippets.

@jeanlescure
Created August 8, 2023 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeanlescure/21b07b19b0c1f67baefec8f7a11f51f9 to your computer and use it in GitHub Desktop.
Save jeanlescure/21b07b19b0c1f67baefec8f7a11f51f9 to your computer and use it in GitHub Desktop.
Interactive BPM tracker using key taps, averaging over N taps for smoother BPM detection in Processing
float bpm = 120;
float minute = 60000;
float interval = minute / bpm;
int time;
int beats = 0;
// Variables for BPM calculation based on key taps
int lastTapTime = 0;
int tapInterval = 0;
// Maximum time allowed between taps (in milliseconds). If exceeded, the next tap is considered the "first" tap.
int maxTimeBetweenTaps = 2000; // 2 seconds for example
// List to store the intervals between taps
ArrayList<Integer> tapIntervals = new ArrayList<Integer>();
int numberOfTapsToAverage = 5;
void setup() {
size(300, 300);
fill(255, 0, 0);
noStroke();
time = millis();
}
void draw() {
background(255);
if (millis() - time > interval ) {
ellipse(width/2, height/2, 50, 50);
beats++;
time = millis();
}
text(beats, 30, height - 25);
text("BPM: " + bpm, 30, height - 50);
}
void keyPressed() {
int currentTapTime = millis();
// If the time between the current tap and the last tap exceeds maxTimeBetweenTaps, reset lastTapTime and clear the tapIntervals list
if (currentTapTime - lastTapTime > maxTimeBetweenTaps) {
lastTapTime = 0;
tapIntervals.clear();
}
// If it's not the first tap, calculate the BPM
if (lastTapTime != 0) {
tapInterval = currentTapTime - lastTapTime;
tapIntervals.add(tapInterval);
// If we have enough taps, calculate the average BPM
if (tapIntervals.size() == numberOfTapsToAverage) {
int totalInterval = 0;
for (int i = 0; i < tapIntervals.size(); i++) {
totalInterval += tapIntervals.get(i);
}
int averageInterval = totalInterval / numberOfTapsToAverage;
bpm = 60000.0 / averageInterval;
interval = averageInterval;
beats = 0;
// Remove the oldest tap interval to make room for the next one
tapIntervals.remove(0);
}
}
lastTapTime = currentTapTime;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment