Search code examples
javascripthtmlaudiohtml5-audioweb-audio-api

Web Audio API: Stop all scheduled sounds from playing


So i have a bunch of loaded audio samples that I am calling the schedule function with in the code below:

let audio;

function playChannel() {
    let audioStart = context.currentTime;
    let next = 0;

    for(let i = 0; i < 8; i++) {
        scheduler(audioStart, next);
        next++;
    }
}

Here is the audio scheduler function:

function scheduler(audioStart, index) {
    audio = context.createBufferSource(); 
    audio.buffer = audioSamples[index];  //array with all the loaded audio
    audio.connect(context.destination);  
    audio.start(audioStart + (audio.buffer.duration * index));
}

And it's working fine and plays the scheduled sounds as it should.

How am I supposed to stop/cancel all the scheduled sounds from playing?

Because right now when I try to call the stop() method it will only stop the last scheduled sound from playing.


Solution

  • You'll need to keep track of the BufferSource nodes you're creating inside scheduler, referenced by index, and then run through all of them. E.g.:

    var sources = [];
    
    function scheduler(audioStart, index) {
        audio = context.createBufferSource();
        sources[index] = audio; 
        audio.buffer = audioSamples[index];  //array with all the loaded audio
        audio.connect(context.destination);  
        audio.start(audioStart + (audio.buffer.duration * index));
    }
    
    function stopAll() {
        for(let i = 0; i < 8; i++)
            if (sources[i])
              sources[i].stop(0);
    }