两次播放后动态声音无法播放

时间:2012-10-14 16:53:13

标签: javascript jquery html audio

我有一个小的html5应用程序,您可以通过单击按钮播放声音。

我有一个功能,可以向<audio>添加<div>标记,其ID为“播放”。完成后声音自动消失。

function sound(track){
$("#playing").append("<audio src=\"" + track + "\" autoplay onended=\"$(this).remove()\"></audio>");
}

对于我有的按钮:

<button onclick="sound('sounds/tada.mp3')">Tada</button>

当我点击按钮时,元素检查器中会短暂显示<audio>,并在完成时消失,就像我想要的那样,但在触发它两次后,它就会停止在Chrome中工作,最小。控制台中也没有错误。

发生了什么事?

2 个答案:

答案 0 :(得分:1)

删除HTML中的onclick / onend并引用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();
});

答案 1 :(得分:1)

好的,我们看看..

&#13;
&#13;
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);
&#13;
<div id="playing">
  
</div>
<button id="tada">Tada</button>
&#13;
&#13;
&#13;

我没有看到此脚本出现任何问题。

  1. 决定audioURL,将audioEl设置为null,因为稍后将会使用
  2. 点击ID为"tada"的元素后,运行我们的sound功能。
    • 删除音频。
    • 创建音频元素。
    • 音频播放完毕后,请删除音频。
    • 将音频附加到ID为"playing"的元素。
    • 播放音频。
  3. 需要注意的一点是,我使用的是ended事件,而不是end事件。

    (This answer is here because Andrew really wants us to answer it.)

相关问题