Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove properly html5 audio without appending to DOM?

With Javascript, I have a function that creates an audio element with createElement("audio"), and start playing in loop without using appendChild(), I mean without appending it to the DOM. The element created is kept in a variable, let's called it music1:

music = document.createElement("audio");
 music.addEventListener("loadeddata", function() {
 music.play();
});
music.setAttribute("src", music_Source);

What I would like to do, is to change the music played, if possible using the same function, and storing the element in the same variable.

What I do is that before the code above:

if(typeof(music) == "object") {
 music.pause();
 music = null;
}

But: if I remove music.pause(), the first music keeps playing, and the second starts playing too at the same time, which makes me think that the first music is always somewhere in the document/in the memory. Also, music = null seems useless. I don't want to use jQuery.

Do you have any idea to properly remove the first music, delete the element, or so on?

Actually, kennis' comment is right, I tried to just change the src attribute, and not modify the "music" variable (neither setting it to null, nor re-creating an Element) and it seem to work too. So, for the record: For each source changing here is the 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);
like image 723
Jo Pango Avatar asked Jan 14 '12 19:01

Jo Pango


2 Answers

rather than delete, the better way of doing it would be to change the src

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

that way you're always dealing with the same object so you hit the DOM less often, and also you avoid your problem of having two player at the same time

Also make sure you use the .load method to load the new audio, otherwise it will keep playing the old one.

like image 159
Last Rose Studios Avatar answered Oct 01 '22 12:10

Last Rose Studios


The original object would be deleted, but only when the garbage collector determines that it's time. The fact that it's audio may complicate things and make it difficult for the browser to make that determination.

So, yes, just re-use the original object instead.

like image 30
Lightness Races in Orbit Avatar answered Oct 01 '22 12:10

Lightness Races in Orbit