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

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

有什么建议吗?


当前回答

如果你的网站上有几个音频播放器,你想暂停它们:

$('audio').each( function() {
    $(this)[0].pause();
});

其他回答

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

代码中的某个地方:

audioCh1: document.createElement("audio");

然后在stop()中:

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

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

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.

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

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

就像这样改变,

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

这个方法有效:

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

但如果你不想每次停止音频时都写这两行代码,你可以做以下两件事之一。第二个我认为是更合适的,我不知道为什么“javascript标准之神”没有制定这个标准。

第一种方法:创建一个函数并传递音频

function stopAudio(audio) {
    audio.pause();
    audio.currentTime = 0;
}

//then using it:
stopAudio(audio);

第二种方法(首选):扩展Audio类:

Audio.prototype.stop = function() {
    this.pause();
    this.currentTime = 0;
};

我有一个javascript文件,我称之为“AudioPlus.js”,我包括在我的html之前的任何脚本,将处理音频。

然后你可以在音频对象上调用stop函数:

audio.stop();

最后CHROME的问题与“canplaythrough”:

我没有在所有浏览器中测试这个,但这是我在Chrome中遇到的一个问题。如果你尝试在一个音频上设置currentTime,该音频有一个“canplaythrough”事件监听器附加到它,那么你将再次触发该事件,这可能会导致不期望的结果。

因此,解决方案是在第一次调用之后删除事件侦听器,这与附加了一个事件侦听器并且确实希望确保它不会再次触发的所有情况类似。就像这样:

//note using jquery to attach the event. You can use plain javascript as well of course.
$(audio).on("canplaythrough", function() {
    $(this).off("canplaythrough");

    // rest of the code ...
});

奖金:

请注意,您可以向Audio类(或任何本地javascript类)添加更多自定义方法。

例如,如果你想要一个“restart”方法重新启动音频,它可以是这样的:

Audio.prototype.restart= function() {
    this.pause();
    this.currentTime = 0;
    this.play();
};

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

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

这应该会有预期的效果。