我正在播放一个小音频剪辑点击每个链接在我的导航

HTML代码:

<audio tabindex="0" id="beep-one" controls preload="auto" >
    <source src="audio/Output 1-2.mp3">
    <source src="audio/Output 1-2.ogg">
</audio>

JS代码:

$('#links a').click(function(e) {
    e.preventDefault();
    var beepOne = $("#beep-one")[0];
    beepOne.play();
});

到目前为止一切正常。

问题是当一个声音剪辑已经运行,我点击任何链接没有发生。

我试图停止点击链接时已经播放的声音,但在HTML5的音频API中没有直接事件

我试着遵循代码,但它不工作

$.each($('audio'), function () {
    $(this).stop();
});

有什么建议吗?


当前回答

作为旁注,因为我最近使用了在接受的答案中提供的停止方法,根据这个链接:

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events

手动设置currentTime可以触发音频元素上的canplaythrough事件。在链接中,它提到了Firefox,但我在Chrome上手动设置currentTime后遇到了这个事件。所以如果你有行为附加到这个事件,你可能会在一个音频循环中结束。

其他回答

这种方法是“蛮力”的,但前提是“允许”使用jQuery。围绕你的“player”<audio></audio>标签与div(这里与id“plHolder”)。

<div id="plHolder">
     <audio controls id="player">
     ...
     </audio>
<div>

然后这个javascript应该工作:

function stopAudio() {
    var savePlayer = $('#plHolder').html(); // Save player code
    $('#player').remove(); // Remove player from DOM
    $('#FlHolder').html(savePlayer); // Restore it
}

而不是stop(),你可以尝试:

sound.pause();
sound.currentTime = 0;

这应该会有预期的效果。

我喜欢做的是使用Angular2完全删除控件,然后当下一首歌有音频路径时,它会被重新加载:

<audio id="audioplayer" *ngIf="song?.audio_path">

然后当我想在代码中卸载它时,我这样做:

this.song = Object.assign({},this.song,{audio_path: null});

当下一首歌曲被分配时,控件完全从头开始重新创建:

this.song = this.songOnDeck;

解决这个错误的简单方法是捕获错误。

audioElement.play()返回一个承诺,所以下面带有.catch()的代码应该足以处理这个问题:

函数playSound(声音){ sfx.pause (); 自解压。currentTime = 0; 自解压。SRC =声音; sfx.play()。Catch (e => e); }

注意:为了向后兼容,您可能需要将箭头函数替换为匿名函数。

我也有同样的问题。如果它是一台收音机,停止应该停止流和播放去直播。我看到的所有解决方案都有一个缺点:

的球员。currentTime = 0继续下载流。 的球员。SRC = "引发错误事件。

我的解决方案:

var player = document.getElementById('radio');
player.pause();
player.src = player.src;

还有HTML

<audio src="http://radio-stream" id="radio" class="hidden" preload="none"></audio>