动态声音在两次播放后不播放
我有一个小小的html5应用程序,您可以通过单击按钮播放声音。动态声音在两次播放后不播放
我有一个功能,将<audio>
标记添加到ID为“正在播放”的<div>
。完成后,声音会自行消失。
function sound(track){
$("#playing").append("<audio src=\"" + track + "\" autoplay onended=\"$(this).remove()\"></audio>");
}
对于按钮我:
<button onclick="sound('sounds/tada.mp3')">Tada</button>
当我点击按钮,<audio>
短暂出现在元素检查,当它完成,只是我想要的方式消失,但后触发它两次,至少在Chrome中停止工作。控制台中也没有错误。
这是怎么回事?
摆脱的onclick的/ onend在你的HTML和引用您的JS按钮:
HTML
<button id='tada' sound_url='sounds/tada.mp3'>Tada</button>
而且JS
var sound = function(track){
$("#playing").append("<audio id='played_audio' src='\" + track + \"' autoplay='true'></audio>");
}
$('#tada').on('click', function() {
var sound_url = $(this).attr('sound_url');
sound(sound_url);
});
$('#playing').on('end', 'played_audio', function() {
$(this).remove();
});
有趣....我会稍后尝试 –
好吧,让我们看看..
var audioURL = "http://soundbible.com/mp3/Canadian Geese-SoundBible.com-56609871.mp3";
var audioEl = null;
function removeAudio() {
if (audioEl && audioEl.parentNode)
audioEl.parentNode.removeChild(audioEl);
}
function sound() {
removeAudio();
audioEl = document.createElement("audio");
audioEl.src = audioURL;
audioEl.controls = true;
audioEl.addEventListener("ended", removeAudio); // <-- Note it's ended, not end!
document.getElementById("playing").appendChild(audioEl);
audioEl.play();
}
document.getElementById("tada").addEventListener("click", sound);
<div id="playing">
</div>
<button id="tada">Tada</button>
我没有看到这个脚本的任何问题。
- 决定audioURL,设置audioEl为null,因为它会在稍后
- 当单击带有ID
"tada"
元素中使用,运行我们sound
功能。- 删除音频。
- 创建音频元素。
- 音频结束后,请取出音频。
- 将音频追加到ID为的元素。
- 播放音频。
有一点要注意的是,我用的是ended
事件,而不是end
事件。
(This answer is here because Andrew really wants us to answer it.)
有趣!让我在我缓慢的小型上网本上进行测试,这显然是触发问题的一个因素。 –
你能提供一个小提琴链接吗? – StaticVariable
小提琴:http://jsfiddle.net/EMngS/ –
+1为田田音 – goat