Why does this tone.js audio sequence play inconsistently after the first time?

33 Views Asked by At

Using tone js, I created a sequence of notes to be played when an html button calls the play() function. However it only plays the sequence consistently on the first button press after each page load. After that the time interval between the notes is inconsistent.

// variable declarations
const synth = new Tone.Synth().toDestination();
let duration = "8n";
let sequence = ["C3", "A3", "B3"];
let i = 0;

// loops through the notes of the "sequence" variable
function playSequence() {
    if (Tone.context.state != "running") {Tone.start();}
    synth.triggerAttackRelease(sequence[i], duration);
    i++;
    if (i >= sequence.length) {clearInterval(sequenceInterval);}
}

// triggers the play notes function repeatedly at a time interval
function play() {i = 0; const sequenceInterval = setInterval(playSequence, 600);}

I can't think of a reason why this would only work well the first time. Any idea why? (Also very occasionally it does play it oddly the first time as well)

1

There are 1 best solutions below

0
darkplasma On

Well, I don't know exactly what was wrong, but this works consistently when play() is called.

// variable declarations
const synth = new Tone.Synth().toDestination();
let duration = "8n";
let noteSequence = ["C3", "A3", "B3"];
let timeInterval = 700
let i = 0;

// Loops through the notes
function play() {
    var counter = 0; 
    i = 0;
    var intervalLoop = setInterval(function() {
        if (Tone.context.state != "running") {Tone.start();}

        
        synth.triggerAttackRelease(noteSequence[i], duration);
        i++;

        counter++; if (counter === noteSequence.length) {clearInterval(intervalLoop);}
    }, timeInterval);
}