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

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

有什么建议吗?


当前回答

而不是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.

我在寻找一些类似的东西,因为制作一个应用程序,可以用来图层彼此的声音聚焦。我最终做的是-当选择一个声音时,用Javascript创建音频元素:

                const audio = document.createElement('audio') as HTMLAudioElement;
                audio.src = getSoundURL(clickedTrackId);
                audio.id = `${clickedTrackId}-audio`;
                console.log(audio.id);
                audio.volume = 20/100;
                audio.load();
                audio.play();

然后,附加子文件实际上表面的音频元素

document.body.appendChild(audio);

最后,当取消选择音频时,您可以停止并完全删除音频元素-这也将停止流。

            const audio = document.getElementById(`${clickedTrackId}-audio`) as HTMLAudioElement;
            audio.pause();
            audio.remove();

在IE 11中,我使用了组合变体:

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

只有2次重复可以防止IE在pause()后继续加载媒体流,并因此淹没磁盘。

我相信检查音频是否处于播放状态并重置currentTime属性会很好。

if (sound.currentTime !== 0 && (sound.currentTime > 0 && sound.currentTime < sound.duration) {
    sound.currentTime = 0;
}
sound.play();

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

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

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

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

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

this.song = this.songOnDeck;