I'm trying to find out what the best way to play synchronised Audio tracks through the Web Audio API is. What i'm trying to achieve is to play multiple .wav files at once with as little delay in synchronisation of the audio tracks as possible.
The only way i've found to play multiple audio tracks at the same time is to create multiple audio tracks and loop through them in a for loop. The issue with this is that there's a tiny amount of delay between the loops. The delay is only a couple of milliseconds usually depending on the users machine however when I have something like 30 audio tracks that need to start at the same time and my loop has to loop over 30 tracks and call source.start()
on each of them, there is a noticeable delay by the time the loop starts the 30th track.
As I need the tracks to play as on time as possible, I was wondering if there was perhaps another solution. Maybe for example where via the Web Audio API you could load in multiple sources and then have a native global event that would start all those tracks simultaneously.
Here is some code that shows the issue:
const audioBuffer1 = '...'; // Some decoded audio buffer
const audioBuffer2 = '...'; // some other decoded audio buffer
const audioBuffer3 = '...'; // and another audio buffer
const arrayOfAudioBuffers = [audioBuffer1, audioBuffer2, audioBuffer3];
const context = new AudioContext();
function play(audioBuffer) {
const source = context.createBufferSource();
source.buffer = audioBuffer;
source.connect(context.destination);
source.start();
}
for (let i = 0; i < arrayOfAudioBuffers.length; i++) {
// every time this loops the play function is
// called around 2 milliseconds after the previous
// one causing sounds to get slightly out of sync
play(arrayOfAudioBuffers[i]);
}
An example of an app that uses multiple track sources and manages to keep good synchronisation is Splice Beatmaker. I've explored a few libraries such as Howler and Tone but they appear to use the loop approach I believe.
Would love to hear any suggestions as to how to tackle this issue
from Web Audio API - Playing synchronized sounds
No comments:
Post a Comment