While working on WebAudio experimentation, I encountered an issue with loading a sound using the JavaScript code below.
function playAudio(){
var audio = document.getElementById('music');
var audioContext = new webkitAudioContext();
var analyser = audioContext.createAnalyser();
var source = audioContext.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(audioContext.destination);
audio.play();
}
In addition to playing the sound, I want to visualize it using canvas by utilizing the analyser
. The function works correctly the first time it is used, but upon executing it a second time, an error occurs.
> playAudio(); // successfully plays sound
> playAudio(); // error
InvalidStateError: Failed to execute 'createMediaElementSource' on 'AudioContext': invalid HTMLMediaElement.
The identified cause of this error lies within this specific line of code:
var source = audioContext.createMediaElementSource(audio);
Even though I am creating a new audio context, attempting to reuse the same audio element in the HTML leads to this error.