html – I’m trying to play different audio files on the same html5 canvas analyzer

I have two buttons that I want to play different .mp3s with visual analyzer bar graphs on the same html5 canvas.

I’m not sure how to stop or close the createMediaElementSource() node.

I can’t seem to get the right syntax to do just that:

firstBtn.addEventListener('click', function(){
        if (audioContext) {
            audioContext.close();
        } else{ 
    const audio1 = document.getElementById('audio1');
    audio1.src="https://stackoverflow.com/questions/74036366/myFirst.mp3"
    audio1.controls = true;
    audio1.loop = false;
    audio1.autoplay = false;
        
    const audioContext = new AudioContext();
        audio1.play();
        audioSource = audioContext.createMediaElementSource(audio1);
        analyser = audioContext.createAnalyser();
        audioSource.connect(analyser);
        analyser.connect(audioContext.destination);

Then the second button eventListener:

secondBtn.addEventListener('click', function(){
        if (audioContext) {
            audioContext.close();
        } else{ 
    const audio1 = document.getElementById('audio1');
    audio1.src="https://stackoverflow.com/questions/74036366/mySecond.mp3"
    audio1.controls = true;
    audio1.loop = false;
    audio1.autoplay = false;
        
    const audioContext = new AudioContext();
        audio1.play();
        audioSource = audioContext.createMediaElementSource(audio1);
        analyser = audioContext.createAnalyser();
        audioSource.connect(analyser);
        analyser.connect(audioContext.destination);

Any help would be greatly appreciated!

Read more here: Source link