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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With