JSFiddle - React, Tailwind, and code Playground
JavaScript
function noteDurationToMs (bpm, dur, type) {
return 60000 * 4 * dur * type / bpm
}
function scheduleNote(ac, time, dur) {
var osc = ac.createOscillator();
osc.connect( ac.destination );
osc.start(time);
osc.stop(time + dur);
}
const ac = new AudioContext();
let lastNote= ac.currentTime;
const step = noteDurationToMs(120, 1 / 4, 1) / 1000;
const lookAhead = step / 2;
setInterval(()=> {
const diff = ac.currentTime - lastNote;
if (diff >= lookAhead) {
const nextNote = lastNote + step;
scheduleNote(ac, nextNote, 0.025)
lastNote = nextNote;
}
},15)