With Javascript, I have a function that creates an audio element with createElement("audio") and starts playing in a loop without using appendChild() , I mean, without adding it to the DOM. The created element is stored in a variable, let it be called music1 :
music = document.createElement("audio"); music.addEventListener("loadeddata", function() { music.play(); }); music.setAttribute("src", music_Source);
What I would like to do is change the music being played, if possible, using the same function and save the item in the same variable.
What I am doing is before the code above:
if(typeof(music) == "object") { music.pause(); music = null; }
But: if I delete music.pause() , the first music continues to play, and the second starts playing at the same time, which makes me think that the first music is always somewhere in the document / in memory. In addition, music = null seems useless. I do not want to use jQuery.
Do you have an idea to delete the first music correctly, delete an item or so on?
Actually, kennis's comment is right, I just tried to change the src attribute and not change the "music" variable (neither setting it to zero, nor re-creating Element), and it seems to work too. So, for the record: for every source that changes here, there is a function:
if(typeof(music) != "object") { //audio element does not exist yet: music = document.createElement("audio"); music.addEventListener("loadeddata", function() { music.play(); }); } music.setAttribute("src", music_Source);
javascript html5 audio
Jo pango
source share