Trying to create a simple drum machine sequencing app without using any libraries. Basic purpose of the app is to loop audio at specified intervals while some sort of condition is met e.g. pressing the spacebar.
I figured out that looping audio with setInterval isn't really a good idea since it's pretty inconsistent. Found another solution using new Date()
but the example requires calling the function with a set duration as an arg. What I'd like to do is use this same code, but have the loop run infinitely until a spacebar keydown or some other condition is met.
Is this possible? Any thoughts on how I can adapt or re-write this to get what I want? I know how to create my trigger for the loop with event handlers, but each keydown or whatever event will trigger a new audio event (causing loops on top of loops) vs. killing the process of the last one which once set to "loop forever" does just that...
function doTimer(totalms, interval, oninstance, kill) {
var time = 0,
start = new Date().getTime();
function instance() {
time += interval;
if (kill) {
} else {
var diff = (new Date().getTime() - start) - time;
window.setTimeout(instance, (interval - diff));
oninstance(time + diff);
}
}
window.setTimeout(instance, interval);
}
function playSample(str){
soundStr = `./audio808/${str}.mp3`;
sound = new Audio(soundStr);
sound.play();
}
doTimer(0, // duration
125, // sets the interval
function() {
playSample("ch");}, // calls the sample to play
true // whether or not it should play
);