javascriptaudiocontext

How can I programmatically determine when an JavaScript AudioContext AudioBufferSource is done playing?


I am playing .MP3 files with the Web Audio API, and I am having trouble programmatically determining when the song is finished playing.

This is what I have:

var request = new XMLHttpRequest();

audioContext = new AudioContext();

source = audioContext.createBufferSource();
source.connect(audioContext.destination);

request.open('GET',url,true);
request.responseType='arraybuffer';
request.onload = function() {
    audioContext.decodeAudioData(request.response).then(function(buffer) {
        source.buffer = buffer;
        source.start(0);
    });
}   
request.send();

This works well; I can start, stop, pause, and unpause a song with no problems.

What I want to do, however, is when a song stops playing upon completion (i.e., I have not called audioContext.close()), I want to call another function to set a message for the user. I have looked for some sort of callback I could leverage, I have tried the finally() of the promise provided by the audioContext.decodeAudioData() provides, but I haven't been able to figure this out.


Solution

  • Handle the ended event of your audioContext. See AudioScheduledSourceNode: ended event for reference.

    source.addEventListener('ended', () => {
       // done!
    });
    

    Or use the onended property.

    source.onended = () => {
      // done!
    }