Search code examples
javascriptweb-audio-api

Why can't a recursive onended property of an oscillator be used to create a music sequencer?


Im curious why the oscillators onended method can't be used to create a music sequencer and why using the "two clocks" method is better.

Here is a rough (kinda working ) code sketch of what I'm thinking.

var x = oscillator.onended = function() {
        oscillator = audioContext.createOscillator();
        oscillator.frequency.value = 0;
        oscillator.connect(audioContext.destination);
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.000001);


        oscillator.onended = function() {

            if (Math.abs(item - audioContext.currentTime) >= 1) {
                if (tick === 8) {
                    tick = 1;

                } else {
                    item = audioContext.currentTime;
                    tick += 1;
                    sounds.kick.play();
                }


            }



            x()


        }
    }

Solution

  • This probably doesn't quite work as you want because you can't depend on exactly when onended is fired. There's probably going to be a random gap between when one oscillator stops and the next begins.