Html HTML5 音频停止功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14834520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:34:37  来源:igfitidea点击:

HTML5 Audio stop function

htmlhtml5-audio

提问by Alok Jain

I am playing a small audio clip on click of each link in my navigation

单击导航中的每个链接时,我正在播放一个小音频剪辑

HTML Code:

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 code:

JS代码:

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

It's working fine so far.

到目前为止它运行良好。

Issue is when a sound clip is already running and i click on any link nothing happens.

问题是当声音剪辑已经在运行时,我点击任何链接没有任何反应。

I tried to stop the already playing sound on click of link, but there is no direct event for that in HTML5's Audio API

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

I tried following code but it's not working

我尝试了以下代码,但它不起作用

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

Any suggestions please?

请问有什么建议吗?

回答by kr1

Instead of stop()you could try with:

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

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

This should have the desired effect.

这应该会产生预期的效果。

回答by zaki

first you have to set an id for your audio element

首先你必须为你的音频元素设置一个 id

in your js :

在你的 js 中:

var ply = document.getElementById('player');

var ply = document.getElementById('player');

var oldSrc = ply.src;// just to remember the old source

var oldSrc = ply.src;// 只是为了记住旧的来源

ply.src = "";// to stop the player you have to replace the source with nothing

ply.src = "";// 要停止播放器,您必须将源替换为空

回答by MrHetii

Here is my way of doing stop() method:

这是我执行 stop() 方法的方式:

Somewhere in code:

代码中的某处:

audioCh1: document.createElement("audio");

and then in stop():

然后在 stop() 中:

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

In this way we don`t produce additional request, the old one is cancelled and our audio element is in clean state (tested in Chrome and FF) :>

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

回答by Mikel

I was having same issue. A stop should stop the stream and onplay go to liveif it is a radio. All solutions I saw had a disadvantage:

我有同样的问题。如果是收音机,则停止应该停止流并且 onplay 开始直播。我看到的所有解决方案都有一个缺点

  • player.currentTime = 0keeps downloading the stream.
  • player.src = ''raise errorevent
  • player.currentTime = 0不断下载流。
  • player.src = ''引发error事件

My solution:

我的解决方案:

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

And the HTML

和 HTML

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

回答by Zuks

This method works:

这种方法有效:

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

But if you don't want to have to write these two lines of code every time you stop an audio you could do one of two things. The second I think is the more appropriate one and I'm not sure why the "gods of javascript standards" have not made this standard.

但是,如果您不想在每次停止音频时都编写这两行代码,则可以执行以下两种操作之一。我认为第二个更合适,我不确定为什么“javascript 标准之神”没有制定这个标准。

First method: create a function and pass the audio

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

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

//then using it:
stopAudio(audio);

Second method (favoured): extend the Audio class:

第二种方法(推荐):扩展 Audio 类:

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

I have this in a javascript file I called "AudioPlus.js" which I include in my html before any script that will be dealing with audio.

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

Then you can call the stop function on audio objects:

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

audio.stop();

FINALLY CHROME ISSUE WITH "canplaythrough":

最后是“canplaythrough”的 Chrome 问题:

I have not tested this in all browsers but this is a problem I came across in Chrome. If you try to set currentTime on an audio that has a "canplaythrough" event listener attached to it then you will trigger that event again which can lead to undesirable results.

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

So the solution, similar to all cases when you have attached an event listener that you really want to make sure it is not triggered again, is to remove the event listener after the first call. Something like this:

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

//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 ...
});

BONUS:

奖金:

Note that you can add even more custom methods to the Audio class (or any native javascript class for that matter).

请注意,您可以向 Audio 类(或任何与此相关的本机 javascript 类)添加更多自定义方法。

For example if you wanted a "restart" method that restarted the audio it could look something like:

例如,如果您想要一个重新启动音频的“重新启动”方法,它可能如下所示:

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

回答by James Groves

From my own javascript function to toggle Play/Pause - since I'm handling a radio stream, I wanted it to clear the buffer so that the listener does not end up coming out of sync with the radio station.

从我自己的 javascript 函数切换播放/暂停 - 由于我正在处理广播流,我希望它清除缓冲区,以便听众最终不会与广播电台不同步。

function playStream() {

        var player = document.getElementById('player');

        (player.paused == true) ? toggle(0) : toggle(1);

}

function toggle(state) {

        var player = document.getElementById('player');
        var link = document.getElementById('radio-link');
        var src = "http://192.81.248.91:8159/;";

        switch(state) {
                case 0:
                        player.src = src;
                        player.load();
                        player.play();
                        link.innerHTML = 'Pause';
                        player_state = 1;
                        break;
                case 1:
                        player.pause();
                        player.currentTime = 0;
                        player.src = '';
                        link.innerHTML = 'Play';
                        player_state = 0;
                        break;
        }
}

Turns out, just clearing the currentTime doesn't cut it under Chrome, needed to clear the source too and load it back in. Hope this helps.

事实证明,仅清除 currentTime 并不能在 Chrome 下剪切它,也需要清除源并将其重新加载。希望这会有所帮助。

回答by shamangeorge

As a side note and because I was recently using the stop method provided in the accepted answer, according to this link:

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

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

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

by setting currentTime manually one may fire the 'canplaythrough' event on the audio element. In the link it mentions Firefox, but I encountered this event firing after setting currentTime manually on Chrome. So if you have behavior attached to this event you might end up in an audio loop.

通过手动设置 currentTime 可以触发音频元素上的 'canplaythrough' 事件。在链接中它提到了 Firefox,但我在 Chrome 上手动设置 currentTime 后遇到了这个事件触发。因此,如果您将行为附加到此事件,您可能最终会陷入音频循环。

回答by Ola Tuvesson

shamangeorge wrote:

沙曼乔治写道:

by setting currentTime manually one may fire the 'canplaythrough' event on the audio element.

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

This is indeed what will happen, and pausing will also trigger the pauseevent, both of which make this technique unsuitable for use as a "stop" method. Moreover, setting the srcas suggested by zaki will make the player try to load the current page's URL as a media file (and fail) if autoplayis enabled - setting srcto nullis 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.

这确实会发生,暂停也会触发pause事件,这两种情况都使得这种技术不适合用作“停止”方法。此外,src按照 zaki 的建议设置将使播放器尝试将当前页面的 URL 作为媒体文件加载(并且失败)如果autoplay启用 - 设置srcnull不允许;它将始终被视为一个 URL。除了销毁播放器对象,似乎没有提供“停止”方法的好方法,所以我建议只删除专用的停止按钮并提供暂停和后退按钮 - 停止按钮不会真正添加任何功能.

回答by gogog

It don't work sometimes in chrome,

它有时在 chrome 中不起作用,

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

just change like that,

就这样改

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

回答by user3062615

This approach is "brute force", but it works assuming using jQuery is "allowed". Surround your "player" <audio></audio>tags with a div (here with an id of "plHolder").

这种方法是“蛮力”,但它的工作原理是假设使用 jQuery 是“允许的”。<audio></audio>用 div包围你的“玩家”标签(这里的 id 为“plHolder”)。

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

Then this javascript should work:

那么这个javascript应该可以工作:

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