【问题标题】:Dynamic sounds not playing after two plays播放两次后动态声音不播放
【发布时间】:2012-10-14 16:53:13
【问题描述】:

我有一个小的 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>

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

发生了什么事?

【问题讨论】:

标签: javascript jquery html audio


【解决方案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();
});

【讨论】:

    【解决方案2】:

    好的,让我们看看..

    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 事件。

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

    【讨论】:

    • 有趣!让我在我的速度慢的小上网本上测试一下,这显然是引发问题的一个因素。
    猜你喜欢
    • 1970-01-01
    • 2015-03-03
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多