How to set up audio output device in Babylon js using Web Audio API?

Hello there!

I’m not very familiar with Babylon js and Web APIs.

I’m trying to set up “CABLE Input (VB-Audio Virtual Cable)” virtual device as an audio output device, but I don’t understand how to do it in the Babylon Engine.

I have already tried play sound using Web API and it works:

async function sound_test() {
    let deviceId = await select_output_device()
    const audioWavFile = "sounds/violons11.wav"
    const audio = new Audio(audioWavFile)
    await audio.setSinkId?.(deviceId);;

async function select_output_device() {
    if (!navigator.mediaDevices.selectAudioOutput) {
        console.log("selectAudioOutput() not supported or not in secure context.");
        throw Error("selectAudioOutput() not supported or not in secure context.")

    // Display prompt to select device
    const audioDevice = await navigator.mediaDevices.selectAudioOutput();
    return audioDevice.deviceId;

full example:

But how can I do it with Babylon Sound?
I have tried this, but it doesn’t seem to work properly:

const audioWavFile = "sounds/violons11.wav"

const audioContext = new AudioContext();
const audio = document.createElement("audio");
const source = audioContext.createMediaElementSource(audio)
const gain = audioContext.createGain();

const audioEngine = new BABYLON.AudioEngine(
audioEngine.masterGain = gain;


audio.src = audioWavFile;

button2.onPointerUpObservable.add(async () => {
        let deviceId = await select_output_device()
        await audio.setSinkId?.(deviceId);;

full example:

Please, help =)

(Babylon.js 6.0.0)

1 Like

Apologies for not answering earlier? Let me tag the king of audio @docEdub

It took a while to figure out, but I got this working. Unfortunately, it only lets you set the audio device once. If you try setting it again, it fails due to the way the audio engine is designed.

Here’s the modified playground:

If you need to change the audio device more than once, then we’ll need to make some changes to how the audio engine works.

Do you need to change the audio device more than once?

Note to other readers: this currently only works on Firefox because it’s using the new MediaDevices.selectAudioOutput function. See and Firefox is the only browser that supports it right now.

1 Like