fatlinesofcode
fatlinesofcode

Reputation: 1667

Web Audio API, events?

Is it possible to add event listeners to web audio api sounds? I've been looking for an event or trigger for when a sounds completes but can't find anything. Here is how I imagine it would work:

soundSource = context.createBufferSource();
soundBuffer = context.createBuffer(audioData, true);
soundSource.buffer = soundBuffer;
soundSource.connect(volumeNode);
soundSource.addEventListener('ended', function(e){
    console.log("ended", "", e);
}, false);
soundSource.noteOn(context.currentTime);

Upvotes: 13

Views: 9669

Answers (3)

vladvlad
vladvlad

Reputation: 106

Yep, looks like it's been added: AudioBufferSourceNode.onended https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/onended

Upvotes: 2

user3204672
user3204672

Reputation: 121

var isFinished = false;
var source = context.createBufferSource();
source.onended = onEnded;
function onEnded() {
    isFinished = true;
    console.log('playback finished');
}

Check this out

Upvotes: 12

Oskar Eriksson
Oskar Eriksson

Reputation: 2641

Not today, no. I know there's been discussions about adding some kind of event system, but it's not in the spec yet (if it ever will be). There is however a playbackState property on buffer sources that you can check out: https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AudioBufferSourceNode

Other than that, you best bet is to use timeouts based on the buffer length and run your callback when that fires.

Upvotes: 5

Related Questions