JESUS ESPINOSA
JESUS ESPINOSA

Reputation: 131

Java Script DOMException Web Audio API audioContext.createMediaElementSource call again the function

Hi everyone i need yours apreciated help i have the next function, this work the first time to press button , but i press again button the audio no work. the console log is this: Uncaught DOMException: Failed to execute 'createMediaElementSource' on 'BaseAudioContext': HTMLMediaElement already connected previously to a different MediaElementSourceNode. at cargar_audio1

¿How can solved this and load the video every time press button?

the code i use is this:

 document.getElementById('audio1').addEventListener('click', function() {
 var mediaElement1 = document.getElementById("ad1"); 
 mediaElement1.src = "audio1.mp3";
 load_audio1();
 });


 var analyser, source;
 function load_audio1() {
 var audio1 = document.getElementById('ad1');
 var audioContext = new AudioContext();
 analyser = audioContext.createAnalyser();
 analyser.minDecibels = -60;
 analyser.maxDecibels = -10;  
 analyser.fftSize = 32;
 source = audioContext.createMediaElementSource(audio1);
 source.connect(analyser);
 analyser.connect(audioContext.destination); 
 audio1.play();
 view_dat_audio();
 }

Upvotes: 0

Views: 737

Answers (1)

treeno
treeno

Reputation: 2600

Assuming "load the video every time press button" means that you want to play the audio-file audio1.mp3 each time the click-event on audio1 is fired, you could do the following:

In order to play the file you need to do two Things:

  1. Initialize the Audio-Graph (creating the analyzer-node and connecting it to an Audio-source etc.)
  2. call play() on the graph

Right now you are doing this in one step in load_audio1() The solution is to separate the initialization and the call to play() and do the initialization only once in the beginning when it is nessecary.

Roughly like this:

document.getElementById('audio1').addEventListener('click', clickHandler);

function clickHandler() {
    if (!audioGraphIsInitialized()) {
        initAudioGraph();
    }

    audio1.play();
}

Upvotes: 1

Related Questions