Search code examples
javascriptweb-audio-api

Web Audio API - Getting the current offset in a song & onstarted event for a source


I'm playing a segment of a music track using a source in the Web Audio API.

var source = audioCtx.createBufferSource();

source.buffer = audioBuffer;
source.connect(audioCtx.destination);

source.start(when, offset, duration);

I know that there is an event listener that I can use when the source has finished playing, source.onended. Is there an event listener that I can use when the source starts? e.g. source.onstarted?

Furthermore, can at any point get what part of the track is currently playing from a source? Or perhaps even from the audioCtx?

e.g. source.getCurrentOffset(); // 0:21

I would like to avoid my current strategy of starting a setTimeout when the source starts as it's not accurate.

Example

source.start(when, offset, duration);

setTimeout(function() {
    console.log("The track has started!");
}, 1000 * when);

Thanks!


Solution

  • Not sure what you want, but the source starts exactly when you told it to: at time when.

    And currently there's no way to determine where in the buffer the source is playing. People have asked for this feature, but nothing has been done about it in the spec. The returned time will always be inaccurate.