Html 如何在 chrome 上自动播放音频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50490304/
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 15:41:44  来源:igfitidea点击:

How to make audio autoplay on chrome

htmlgoogle-chromehtml5-audio

提问by Akshay Rathod

audio autoplay working in Mozilla, Microsoft edge and old google chrome as well but not in new google chrome. they have blocked the autoplay. is there any way to make it audio autoplay in google chrome?

音频自动播放也适用于 Mozilla、Microsoft Edge 和旧的 google chrome,但不适用于新的 google chrome。他们阻止了自动播放。有没有办法让它在谷歌浏览器中自动播放音频?

回答by jt25

Solution #1

解决方案#1

My solution here is to create an iframe

我的解决方案是创建一个 iframe

<iframe src="audio/source.mp3" allow="autoplay" style="display:none" id="iframeAudio">
</iframe> 

and audiotag aswell for non-chrome browsers

audio为非 Chrome 浏览器标记

<audio autoplay loop  id="playAudio">
    <source src="audio/source.mp3">
</audio>

and in my script

在我的 script

  var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
  if (!isChrome){
      $('#iframeAudio').remove()
  }
  else {
      $('#playAudio').remove() // just to make sure that it will not have 2x audio in the background 
  }

Solution #2:

解决方案#2:

There is also another workaround for this according to @Leonard

根据@Leonard,还有另一种解决方法

Create an iframethat doesn't play anything just to trigger the autoplay in the first load.

创建一个iframe不播放任何内容只是为了在第一次加载时触发自动播放。

<iframe src="silence.mp3" allow="autoplay" id="audio" style="display: none"></iframe>

good source for the mp3 file silence.mp3

mp3文件silence.mp3的好来源

Then play your real audio file at ease.

然后轻松播放您的真实音频文件。

<audio id="player" autoplay loop>
    <source src="audio/source.mp3" type="audio/mp3">
</audio>

Personally I prefer solution #2because it is cleaner approach for not relying so much in JavaScript.

就我个人而言,我更喜欢解决方案 #2,因为它是一种更简洁的方法,无需过多依赖 JavaScript。

Update August 2019

2019 年 8 月更新

Solution #3

解决方案#3

As an alternative we can use <embed>

作为替代,我们可以使用 <embed>

For FirefoxIt seems that audio auto-play is working so we don't need the <embed>element because it will create double audio running.

对于Firefox似乎音频自动播放正在工作,所以我们不需要该<embed>元素,因为它会创建双音频运行。

// index.js
let audioPlaying = true,
    backgroundAudio, browser;
browser = navigator.userAgent.toLowerCase();
$('<audio class="audio1" src="audio.mp3" loop></audio>').prependTo('body');
if (!browser.indexOf('firefox') > -1) {
    $('<embed id="background-audio" src="audio.mp3" autostart="1"></embed>').prependTo('body');
    backgroundAudio = setInterval(function() {
        $("#background-audio").remove();
        $('<embed id="background-audio" src="audio.mp3"></embed>').prependTo('body');
    }, 120000); // 120000 is the duration of your audio which in this case 2 mins.
}

Also if you have a toggle event for your audio make sure to remove the created <embed>element for audio.

此外,如果您的音频有切换事件,请确保删除<embed>为音频创建的元素。

Note:After your toggle, it will restart from the beginning because the <embed>is already deleted and the <audio>element will play as normal now.

注意:切换后,它将从头重新启动,因为<embed>已删除并且<audio>元素现在将正常播放。

$(".toggle-audio").on('click', function(event) {
    audioPlaying = !audioPlaying;
    $("#background-audio").remove();

    clearInterval(backgroundAudio);
    if (audioPlaying){
        $(".audio1").play();
        // play audio 
    }
    else {
        $(".audio1").pause();
    }

And now make sure to hide these <audio>and <embed>elements

现在确保隐藏这些<audio><embed>元素

audio, embed {
    position: absolute;
    z-index: -9999;
}

Note: diplay: noneand visibility: hiddenwill make the <embed>element not work.

注意:diplay: noneandvisibility: hidden会使<embed>元素不起作用。

回答by Leonard Storcks

There is a really neat trick to use the autoplay-function of the audio tag in chrome.

在 chrome 中使用音频标签的自动播放功能有一个非常巧妙的技巧。

Add

添加

<iframe src="silence.mp3" allow="autoplay" id="audio"></iframe>

whereas silence.mp3only is 0.5 seconds of silence.

silence.mp3只有0.5秒的沉默。

This

这个

<audio id="player" autoplay controls><source src="0.mp3" type="audio/mp3"></audio>

works afterwards.

之后工作。

Chrome notices that a sound has been played and gives the permission for autoplay in audio tags.

Chrome 注意到已播放声音并在音频标签中授予自动播放权限。

回答by deltran

As of April 2018, Chrome's autoplay policies changed:

截至 2018 年 4 月,Chrome 的自动播放政策发生了变化:

"Chrome's autoplay policies are simple:

“Chrome 的自动播放政策很简单:

  • Muted autoplay is always allowed.
  • 始终允许静音自动播放。

Autoplay with sound is allowed if:

在以下情况下允许自动播放声音:

  • User has interacted with the domain (click, tap, etc.).
  • On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.
  • On mobile, the user has added the site to his or her home screen.
  • 用户与域进行了交互(单击、点击等)。
  • 在桌面上,用户的媒体参与指数阈值已被超过,这意味着用户之前曾播放过有声视频。
  • 在移动设备上,用户已将站点添加到他或她的主屏幕。

Also

  • Top frames can delegate autoplay permission to their iframes to allow autoplay with sound. "
  • 顶级框架可以将自动播放权限委托给它们的 iframe 以允许自动播放声音。”

Chrome's developer site has more information, including some programming examples, which can be found here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

Chrome 的开发者站点有更多信息,包括一些编程示例,可以在这里找到:https: //developers.google.com/web/updates/2017/09/autoplay-policy-changes

回答by Manuel Alves

Just add this small script as depicted in https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio

只需添加这个小脚本,如https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio 中所述

<head>
<script>
window.onload = function() {
  var context = new AudioContext();
}
</script>
</head>

Than this will work as you want:

比这将如你所愿:

<audio autoplay>
      <source src="hal_9000_sorry_dave.mp3">
</audio>

回答by Paul Becker

At least you can use this:

至少你可以使用这个:

document.addEventListener('click', musicPlay);
function musicPlay() {
    document.getElementById('ID').play();
    document.removeEventListener('click', musicPlay);
}

The music starts when the user clicks anywhere at the page.

当用户点击页面上的任何地方时,音乐就会开始。

It removes also instantly the EventListener, so if you use the audio controls the user can mute or pause it and the music doesn't start again when he clicks somewhere else..

它还会立即删除 EventListener,因此如果您使用音频控件,用户可以将其静音或暂停,并且当他单击其他地方时音乐不会再次开始。

回答by ItsPronounced

Google changed their policies last month regarding auto-play inside Chrome. Please see this announcement.

Google 上个月更改了有关 Chrome 内部自动播放的政策。请参阅此公告

They do, however, allow auto-play if you are embedding a video and it is muted. You can add the mutedproperty and it should allow the video to start playing.

但是,如果您要嵌入视频并且视频已静音,它们确实允许自动播放。您可以添加该muted属性,它应该允许视频开始播放。

<video autoplay controls muted>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>

回答by Murtaza JAFARI

The browsers have changed their privacy to autoplay video or audio due to Ads which is annoying. So you can just trick with below code.

由于烦人的广告,浏览器已将其隐私更改为自动播放视频或音频。所以你可以用下面的代码来欺骗。

You can put any silent audio in the iframe.

您可以在 iframe 中放置任何静音音频。

<iframe src="youraudiofile.mp3" type="audio/mp3" allow="autoplay" id="audio" style="display:none"></iframe>
<audio autoplay>
    <source src="youraudiofile.mp3" type="audio/mp3">
</audio>

Just add an invisible iframe with an .mp3 as its source and allow="autoplay" before the audio element. As a result, the browser is tricked into starting any subsequent audio file. Or autoplay a video that isn't muted.

只需添加一个不可见的 iframe,以 .mp3 作为其源,并在音频元素之前允许 =“自动播放”。结果,浏览器被欺骗启动任何后续的音频文件。或自动播放未静音的视频。

回答by Puto Miké

I've been banging away at this today, and I just wanted to add a little curiosum that I discovered to the discussion.

我今天一直在讨论这个问题,我只是想在讨论中添加一些我发现的好奇心。

Anyway, I've gone off of this:

无论如何,我已经离开了这个:

<iframe src="silence.mp3" allow="autoplay" id="audio" style="display:none"></iframe>
<audio id="audio" autoplay>
  <source src="helloworld.mp3">
</audio>

This:

这个:

<audio id="myAudio" src="helloworld.mp3"></audio>
<script type="text/javascript">
  document.getElementById("myAudio").play();
</script>

And finally this, a "solution" that is somewhat out of bounds if you'd rather just generate your own thing (which we do):

最后,如果您只想生成自己的东西(我们这样做),那么这个“解决方案”有点超出范围:

<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<input onclick='responsiveVoice.speak("Hello World");' type='button' value='Play' />

The discovery I've made and also the truly funny (strange? odd? ridiculous?) part is that in the case of the former two, you can actually beat the system by giving f5 a proper pounding; if you hit refresh repetetively very rapidly (some 5-10 times ought to do the trick), the audio will autoplay and then it will play a few times upon a sigle refresh only to return to it's evil ways. Fantastic!

我的发现以及真正有趣(奇怪?奇怪?荒谬?)的部分是,在前两者的情况下,您实际上可以通过给 f5 适当的冲击来击败系统;如果您非常快速地重复刷新(大约 5-10 次应该可以解决问题),音频将自动播放,然后它会在一次刷新时播放几次,只是为了返回到它的邪恶方式。极好的!

In the announcement from Google it says that for media files to play "automatically", an interaction between the user and the site must have taken place. So the best "solution" that I've managed to come up with thus far is to add a button, rendering the playing of files less than automatic, but a lot more stable/reliable.

在谷歌的公告中,它表示要“自动”播放媒体文件,用户和网站之间必须发生交互。因此,迄今为止我设法想出的最佳“解决方案”是添加一个按钮,使文件的播放不是自动播放,而是更加稳定/可靠。

回答by Juan

Solution without using iframe, or javascript:

不使用 iframe 或 javascript 的解决方案:

<embed src="silence.mp3" type="audio/mp3" autostart="true" hidden="true">
        <audio id="player" autoplay controls><source src="source/audio.mp3" type="audio/mp3"></audio>

With this solution, the open/save dialog of Internet Explorer is also avoided.

使用此解决方案,还避免了 Internet Explorer 的打开/保存对话框。

   <embed src="http://deinesv.cf/silence.mp3" type="audio/mp3" autostart="true" hidden="true">
        <audio id="player" autoplay controls><source src="https://freemusicarchive.org/file/music/ccCommunity/Mild_Wild/a_Alright_Okay_b_See_Through/Mild_Wild_-_Alright_Okay.mp3" type="audio/mp3"></audio>

回答by Akshay Rathod

i used pixi.js and pixi-sound.js to achieve the auto play in chrome and firefox.

我使用 pixi.js 和 pixi-sound.js 在 Chrome 和 firefox 中实现自动播放。

<script>

            PIXI.sound.Sound.from({
            url: 'audios/tuto.mp3',
            loop:true,
            preload: true,
            loaded: function(err, sound) {
                    sound.play();

            document.querySelector("#paused").addEventListener('click', function() {
            const paused = PIXI.sound.togglePauseAll();

            this.className = this.className.replace(/\b(on|off)/g, '');
            this.className += paused ? 'on' : 'off';

            });
            }
            });

</script>

HTML:

HTML:

<button class="btn1 btn-lg off" id="paused">
    <span class="glyphicon glyphicon-pause off"></span>
    <span class="glyphicon glyphicon-play on"></span>
</button>

it also works on mobile devices but user have to touch somewhere on the screen to trigger the sound.

它也适用于移动设备,但用户必须触摸屏幕上的某处才能触发声音。