How to remove html5 audio without adding to the DOM?

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); 
+8
javascript html5 audio
source share
2 answers

instead of deleting, the best way to do this is to change src

 music.setAttribute('src',theNewSource); //change the source music.load(); //load the new source music.play(); //play 

this way you always deal with the same object, so you get into the DOM less often, and also avoid the problems of using two players at the same time.

Also make sure that you use the .load method to load the new audio, otherwise it will continue to play the old one.

+8
source share

The original object will be deleted, but only when the garbage collector determines that it is time. The fact that it is audio can complicate the situation and make it difficult for the browser to determine this.

So yes, just reuse the original object.

+2
source share

All Articles