Search code examples
javascriptaudiocontext

AudioContext .ended not firing properly


I have a simple routine that creates an audiocontext node and loads it with a buffer. The onended event seems to fire at the start. I set a timer for the duration and the onended event triggers about that amount of time before the audio stops playing. Anybody know how to get a true onended event. I tried to use the destination as well as the source, same result

function playSoundFile(buffer) {
   'use strict';
   audioCtx.close();
   audioCtx = new (window.AudioContext || window.webkitAudioContext)();
   audioSource = audioCtx.createBufferSource();
   audioSource.connect(audioCtx.destination);
   audioSource.buffer = buffer;
   audioSource.playbackRate.value = 1;
   stillPlaying(true);
   audio_player = audioCtx.destination;
   audioSource.addEventListener('onended', whatsUp());
   console.log('start ' + showTime());
   filePlayed(buffer.duration);
   audioSource.start();
}

the timestamp is only 1 ms different between the play and the onended event. filePlayed starts a timeout event to show time at beginning and end.


Solution

  • Okay, guest271314 had it mostly right.

    the documentation is confusing. The eventListener is "ended" not "onended" and you have to use function name with the parans

    so

    audioSource.addEventListener('ended', whatsup);
    

    takes care of the problem. Thanks.