Last active
June 14, 2020 19:01
-
-
Save nestarz/18adfe6f8af7f9eeb40c09731fa35bb0 to your computer and use it in GitHub Desktop.
BPM Scheduler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const createScheduler = (ctx, state) => { | |
const callbacks = new Set(); | |
const id = setInterval(() => { | |
const scheduleAheadTime = 0.1; | |
while (state.time < ctx.currentTime + scheduleAheadTime) { | |
callbacks.forEach((callback) => callback(state.beat, state.time)); | |
state.beat += 1; | |
state.time += 60.0 / state.bpm; | |
} | |
}, 25); | |
return { | |
stop: () => clearInterval(id), | |
schedule: (callback) => { | |
callbacks.add(callback); | |
return () => callbacks.delete(callback); | |
}, | |
}; | |
}; | |
const ctx = new AudioContext(); | |
const state = { bpm: 110, beat: 0, time: 0 }; | |
const scheduler = createScheduler(ctx, state); | |
const stop = scheduler.schedule((beat, time) => { | |
const osc = ctx.createOscillator(); | |
osc.frequency.value = beat % 2 ? 300 : 440; | |
osc.start(time); | |
osc.stop(time + 0.1); | |
osc.connect(ctx.destination); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const schedule = (ctx, state, callback) => { | |
const id = setInterval(() => { | |
const scheduleAheadTime = 0.1; | |
while (state.time < ctx.currentTime + scheduleAheadTime) { | |
state.time += 60.0 / state.bpm; | |
state.beat += 1; | |
callback(state.beat, state.time); | |
} | |
}, 25); | |
return () => clearInterval(id); | |
}; | |
const ctx = new AudioContext(); | |
const state = { bpm: 110, beat: 0, time: 0 }; | |
schedule(ctx, state, (beat, time) => { | |
const osc = ctx.createOscillator(); | |
osc.frequency.value = beat % 2 ? 300 : 440; | |
osc.start(time); | |
osc.stop(time + 0.1); | |
osc.connect(ctx.destination); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment