Search code examples
javascripthtml5-audioweb-audio-api

javascript new audioContext mono to Stereo not wordking


I need to convert the mp3 files I play in a project from mono to stereo with the web audio api. But do this a1 = new Audio(/1.mp3); I can't with. My entire system is based on this build. Converting all the sounds playing on the page to stereo or new Audio(/1.mp3); Is there a way to convert a sound created with .

var a1 = new Audio(`/1.mp3`);

a1.volume = .5;
a1.play()

I am using a simple code structure as above.

https://stackoverflow.com/a/54990085/15929287 I couldn't adapt the above answer for myself. In no way can I convert the sound I created with new audio() to stereo. In the example in the link, the oscillator is also added. I'm just trying to do something where I can adjust the mono/stereo setting. I need your help.


Solution

  • The linked answer assumes the mono audio source is an oscillator created with the Web Audio API but it is also possible to use an audio element as the source by using a MediaElementAudioSourceNode.

    The audio graph would then need to be wired up like this:

    const audio = new Audio('/1.mp3');
    const audioCtx = new AudioContext();
    const source = audioCtx.createMediaElementSource(audio);
    const gainNodeL = audioCtx.createGain();
    const gainNodeR = audioCtx.createGain();
    const merger = audioCtx.createChannelMerger(2);
    
    source.connect(gainNodeL);
    source.connect(gainNodeR);
    
    gainNodeL.connect(merger, 0, 0);
    gainNodeR.connect(merger, 0, 1);
    
    merger.connect(audioCtx.destination);
    

    Please note that it's probably still necessary to call resume() on the AudioContext in response to a user gesture to make sure the AudioContext is running.