Search code examples
javascriptaudioweb-audio-api

Web Audio API: Start Multiple MediaElementAudioSourceNode's simultaneously


I am attempting to create a multi-track audio player using the Web Audio API. Currently my play-button click is handled like this...

function playProject(){
    var p = $(".play-button");
    p.hide();
    p.siblings('.pause-button').show();
    for( var i=0 ; i<audio.length ; i++ ){
        audio[i].play();
    }
}

And my Web Audio setup looks like this...

var audioCtx = new (window.AudioContext || window.webkitAudioContext)();

var audio = [];
var channelVolume = [];
var vol = audioCtx.createGain();

$(document).ready(function(){
var obj = JSON.parse('<?php echo $json ?>');

var audioPath = "../wp-content/themes/blankslate-child/projects/"+"<?php echo     $data->name ?>"+"/";

var sources = [];
var merger = audioCtx.createChannelMerger(2);

for(var i = 0; i<obj.length;i++){
    audio.push(new Audio());
    audio[i].src = audioPath+obj[i].name;
    audio[i].loop = true;
    sources.push(audioCtx.createMediaElementSource(audio[i]));
    channelVolume.push(audioCtx.createGain())
    sources[i].connect(channelVolume[i]);
    channelVolume[i].connect(merger,0,0);
}

merger.connect(vol);
vol.connect(audioCtx.destination);

})

Essentially I loop through all of my audio elements and play them. While this works, I feel that it might not be the cleanest way to do it. Is there any way to play all of the audio sources at the same time with a single function call?


Solution

  • This is not possible, the MediaElementAudioSourceNode has no timing guarantees.

    It might work on some browser for example Firefox, in certain cases, and for now, because the way we designed things internally brings you this synchronization, but it might change from a release to the next so I wouldn't depend on it.