如何在不附加DOM的情况下正确删除html5音频? [英] How do I remove properly html5 audio without appending to DOM?

查看:75
本文介绍了如何在不附加DOM的情况下正确删除html5音频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Javascript,我有一个函数可以使用createElement("audio")创建音频元素,并在不使用appendChild()的情况下开始循环播放,我的意思是不将其附加到DOM. 创建的元素保存在变量中,我们称之为music1:

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

但是:如果删除music.pause(),则第一首音乐将继续播放,而第二首音乐也同时开始播放,这使我认为第一首音乐始终位于文档/内存中的某个位置.另外,music = null似乎没有用.我不想使用jQuery.

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?

实际上,kennis的评论是正确的,我试图仅更改src属性,而不修改"music"变量(既不将其设置为null,也不重新创建Element),它似乎也可以工作.因此,为了记录:对于每个更改的源,这里都有函数:

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

推荐答案

与其删除,不如删除它,更好的方法是更改​​src

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

这样一来,您始终会处理同一对象,因此减少了访问DOM的频率,也避免了同时拥有两个玩家的问题

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

还请确保使用.load方法加载新音频,否则它将继续播放旧音频.

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

这篇关于如何在不附加DOM的情况下正确删除html5音频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆