Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop playing sound after specified duration in milliseconds using web audio API

After starting to play audio from an AudioBuffer using AudioBufferSourceNode, how do I make it stop after a predetermined time in milliseconds? My setup is simple:

// create audio source
var source = audioCtx.createBufferSource();

// play audio from source
source.start();

Using AudioBufferSourceNode.stop() I can only specify this duration in seconds, but supplying anything non-integer will evaluate to zero for some reason, and make the audio stop immediately:

source.stop(0.25); // should be 250 milliseconds, but audio stops immediately

setTimeout is not precise enough, and occasional jittering/drifting occurs, especially if the UI works a lot, or other calculations are being performed elsewhere.

setTimeout(function () {
    source.stop(); // very inaccurate
}, 250);

Is there a trivial solution to stop playing an audio after a certain amount of milliseconds, without resorting to hacks like busy wait in a worker thread, or similar?

like image 269
John Weisz Avatar asked Aug 07 '15 13:08

John Weisz


1 Answers

I think you've misunderstood what the first argument to stop() does.

It represents the amount of time relative to the audio context time, which means that when calling stop(), you need to add that time to it:

source.stop(context.currentTime + 0.25);

Since the function accepts a double, it shouldn't be rounding it to the nearest second. According to the Web Audio API specification:

The when parameter describes at what time (in seconds) the sound should stop playing. It is in the same time coordinate system as the AudioContext's currentTime attribute. If 0 is passed in for this value or if the value is less than currentTime, then the sound will stop playing immediately.

like image 162
Qantas 94 Heavy Avatar answered Sep 21 '22 05:09

Qantas 94 Heavy