Web Audio API: Stop all scheduled sounds from playing

与世无争的帅哥 提交于 2020-07-19 06:46:32

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/43454215/web-audio-api-stop-all-scheduled-sounds-from-playing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!