Search code examples
javascripthtmlweb-audio-api

How to change audio source in Web audio APi


I use Web audio Api to spatialize audios, but i cannot find how to simply change the audio file and keep the effects :

const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioContext = new AudioContext();


    // the initial audio
 let audioElement = document.getElementById('underwater-source');
    
 let audioSource = audioContext.createMediaElementSource(audioElement);
        
 const pannerNode = audioContext.createPanner();
 audioSource.connect(pannerNode);
 pannerNode.connect(audioContext.destination);

I use this function to change the audio file. It work but the panning effect doesn't work anymore

function audioSelector(){
    audioElement.pause();
    audioSource.disconnect(pannerNode);
    const a = document.getElementById("audio-select").value;
    audioElement = document.getElementById(`${a}-source`);
    console.log(audioSource.mediaElement)
    audioSource.connect(pannerNode);
    audioElement.play();
}

Solution

  • i've found the solution

     function audioSelector(){
            audioElement.src = document.getElementById("audio-select").value;
            audioElement.play();
        }