pangoweb
pangoweb

Reputation: 484

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);

Upvotes: 14

Views: 35221

Answers (3)

Pieter-Jan Van Robays
Pieter-Jan Van Robays

Reputation: 562

While reusing the HTMLAudioElements is definitely the best option -for completeness- you should be able to dispose it by just clearing the src or srcObj:

music.srcObj = null;

This more or less lets the GC of your browser know that the element is ready for removal.

Upvotes: 1

Last Rose Studios
Last Rose Studios

Reputation: 2481

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.

Upvotes: 18

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

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.

Upvotes: 4

Related Questions