Search code examples
htmlweb-audio-api

How to play multiple AudioBufferSourceNode synchronized?


I have multiple audio files that must be played in sync. I have read that Web Audio API is the best solution for this. But, I can't find any document that shows how to achieve this.

Almost all articles I have read do this to start playback.

//Let's say I have AudioBufferSourceNode connected to two buffers
var source1, source2;

source1.start(0);
source2.start(0);

Shouldn't this cause source2 to start playing slightly later than source1?

Also, what makes the sources stay in sync? I can not find any mention in any documentation that assures that sources are played in sync.

Thanks.


Solution

  • You can schedule them slightly in the future.

    var source1, source2;
    var when = context.currentTime + 0.01;
    
    source1.start(when);
    source2.start(when);
    

    That'll schedule both sounds to play exactly 10ms from the moment you define when. It's quick enough that it'll be perceived as immediate, but gives a bit of breathing room for the overhead of actually calling start on the first source node.

    There are better ways to do this if you have a ton of nodes, but for simple situations, this should be fine.