5

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

我有一个函数可以将<audio>标签添加到<div>id 为“正在播放”的 a 中。完成后声音会自行消失。

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

对于我有的按钮:

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

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

到底是怎么回事?

4

2 回答 2

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();
});
于 2012-10-14T17:21:35.427 回答
1

好吧,让我们看看..

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>

我没有看到这个脚本有任何问题。

  1. 决定audioURL,设置audioEl为null,后面会用到
  2. 当点击带有 ID 的元素时"tada",运行我们的sound函数。
    • 删除音频。
    • 创建音频元素。
    • 音频完成后,删除音频。
    • 将音频附加到 ID 的元素"playing"
    • 播放音频。

需要注意的一点是,我使用的是ended事件,而不是end事件。

(这个答案在这里是因为安德鲁真的希望我们回答它。)

于 2015-10-24T09:00:38.407 回答