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

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();
});

有什么建议吗?


当前回答

在铬合金中有时不能工作,

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

就像这样改变,

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

其他回答

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

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

这应该会有预期的效果。

shamangeorge写道:

手动设置currentTime可以触发音频元素上的canplaythrough事件。

This is indeed what will happen, and pausing will also trigger the pause event, both of which make this technique unsuitable for use as a "stop" method. Moreover, setting the src as suggested by zaki will make the player try to load the current page's URL as a media file (and fail) if autoplay is enabled - setting src to null is not allowed; it will always be treated as a URL. Short of destroying the player object there seems to be no good way of providing a "stop" method, so I would suggest just dropping the dedicated stop button and providing pause and skip back buttons instead - a stop button wouldn't really add any functionality.

这有什么问题吗?

audio.load()

如规范和MDN中所述:

此元素之前播放的任何媒体资源的回放停止。

调用load()将中止所有涉及该媒体元素的正在进行的操作

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

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

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

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

这是我做stop()方法的方式:

代码中的某个地方:

audioCh1: document.createElement("audio");

然后在stop()中:

this.audioCh1.pause()
this.audioCh1.src = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAVFYAAFRWAAABAAgAZGF0YQAAAAA=';

这样我们就不会产生额外的请求,旧的被取消,我们的音频元素处于清洁状态(在Chrome和FF测试):>