138

Audio autoplay is working in Mozilla, Microsoft Edge and old Google Chrome as well but not in Google Chrome 67+ due to a policy change for autoplay.

They have blocked the autoplay (until specific session conditions are met as specified in the linked blogpost). How can one make audio autoplay in Google Chrome 67+?

starball
  • 20,030
  • 7
  • 43
  • 238
Akshay Rathod
  • 1,593
  • 3
  • 10
  • 17
  • 28
    The fact that Google did this is absurd. They literally just said "well no music for your game unless a user clicks Play Music". Unacceptable. So angry! – Hobbes Feb 06 '19 at 18:33
  • 3
    @Hobbes Agreed. At least there should be exceptions. As I mentioned to another poster, I have a "MUSIC" page, with a site link "mymusic.html", which you can only get to with a link/button clearly labeled MY MUSIC". Pretty absurd someone would go there and be surprised or annoyed at sample music being played there. Especially with a clear "fixed position" STOP MUSIC button. This policy is a case of overreaction to abusive practices. – Randy Jun 15 '19 at 23:28
  • 6
    @Randy honestly, and I say this as a musician, I _would_ be annoyed at sample music being played without interaction on a "music" page. I'd expect to see a list of songs, choose which one to hear a sample of, and interact with it to actually hear it – Fox Apr 28 '21 at 15:57
  • 1
    @Fox - I agree with you. Since I made my OP, I've removed all auto play code, even on the browsers that support it or can be fooled. Better to let the visitor be in control. – Randy Apr 29 '21 at 17:02
  • An excellent option is to make your website a single-page-app, then the user will have interacted with the page and autoplay can work after the first click as long as they do not refresh or go to another site. – ktamlyn Mar 20 '22 at 19:32
  • 1
    It was an anti-competitive move by Google. Notice how their own websites are immune to these limitations and can freely auto-play audio without any user interaction. – Enverex Oct 05 '22 at 16:21
  • All the answers here don't work anymore, is there a new recent solution to this? – Thielicious Jun 22 '23 at 15:31

23 Answers23

133

Solution #1

My solution here is to create an iframe

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

and audio tag aswell for non-chrome browsers

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

and in my 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:

There is also another workaround for this according to @Leonard

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

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

good source for the mp3 file 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 #2 because it is cleaner approach for not relying so much in JavaScript.

Update August 2019

Solution #3

As an alternative we can use <embed>

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

// 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.

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.

$(".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 {
    position: absolute;
    z-index: -9999;
}

Note: diplay: none and visibility: hidden will make the <embed> element not work.

Community
  • 1
  • 1
ajbee
  • 3,511
  • 3
  • 29
  • 56
  • How do you make the audio loop? – Kwarrtz Aug 18 '18 at 04:34
  • 1
    Solution 2 worked for me. Sidenote: if you're working for web and Phonegap at the same time, Phonegap doesn't need this workaround and it actually takes it quite bad. So if you have a common codebase for web and Phonegap, make sure you find a way to apply this workaround on web only. – Ignacio Segura Nov 30 '18 at 10:14
  • 2
    The link to the silence file is dead, so I found some other silence files on GitHub: https://github.com/anars/blank-audio . I'm using `1-second-of-silence.mp3` for my project, but any file in this collection would work, I guess. – Travis Dec 19 '18 at 19:10
  • @jt25 How can i make it work in typescript alone. I am trying to play audio from my service file. How can i handle that. I don't have an html to write those tags. Here is my code: const audio = new Audio(); audio.src = 'assets/audios/onlineorder.mp3'; audio.load(); audio.play(); – Anvesh Reddy Mar 12 '19 at 20:41
  • 34
    Seems busted as of Chrome 76. – Shahar 'Dawn' Or Jul 31 '19 at 04:34
  • 9
    Yeah, this doesn't work anymore (if it did work in the past) – Yulian Aug 01 '19 at 13:58
  • 1
    I think so, this solutions doesn't work anymore. I've tried to implement it a long time ago and it's work. But then now this doesn't work anymore. Maybe the browser update their auto play policy, but I didn't get the documentation yet. – Praditha Aug 21 '19 at 02:59
  • 2
    Sounds like this answer might "[now pose security risks or provide code that no longer works](https://meta.stackoverflow.com/q/405302/924299)". – showdev Sep 05 '21 at 01:08
  • 2
    Outdated solutions for now, do not work anymore. – xgqfrms Nov 24 '22 at 12:03
32

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

Add

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

whereas silence.mp3 only is 0.5 seconds of silence.

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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Leonard Storcks
  • 499
  • 6
  • 9
  • 15
    OK, while this does work it also feels like it's exploiting a bug, or at the very least, unintended behaviour. I imagine someone will report this to Google so I wouldn't rely on it working for long. Nice find though! – Neil Bryson Sep 10 '18 at 09:02
  • 8
    Slightly off topic, but your silence.mp3 is quite large at 36.7k. Try this (216 bytes) - https://s3-eu-west-1.amazonaws.com/neilbryson.net.random/silence.mp3 – Neil Bryson Sep 10 '18 at 09:13
  • 3
    silence.mp3 link is dead. You [can create your own](https://stackoverflow.com/a/16714541/79125). – idbrii Dec 13 '18 at 23:13
  • Interesting, I wonder why this method does not work for video as well? – Toniq May 01 '19 at 21:48
  • @Neil Bryson - Can you re upload silence 216 bytes mp3 file? – Toniq May 01 '19 at 21:53
  • 1
    @Toniq Of course, apologies all - https://s3-eu-west-1.amazonaws.com/omegasquadron.neilbryson.net/silence.mp3 – Neil Bryson May 02 '19 at 10:43
  • @LeonardStorcks it was working for me 2 months ago, but it stopped working the moment i went to https – Veer3383 Oct 10 '19 at 10:52
  • 11
    Yeah they're on to it... doesn't work anymore in either Firefox or Chrome – Stefan Reich Jun 25 '20 at 11:52
  • Sounds like this answer might "[now pose security risks or provide code that no longer works](https://meta.stackoverflow.com/q/405302/924299)". – showdev Sep 05 '21 at 01:09
  • seems to me the audio silence is getting downloaded instead of played. any clue for this bugs? – gumuruh Apr 02 '23 at 00:51
  • I don't think this works anymore in 2023... – Adan Vivero Jul 07 '23 at 02:37
24

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

"Chrome's autoplay policies are simple:

  • 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. "

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

deltran
  • 349
  • 1
  • 6
11

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..

Paul Becker
  • 331
  • 1
  • 3
  • 8
  • This I believe is on the right track, of obeying the new policies requiring SOME user interaction to play music. I've added this to the touch event I've already added for mobile browsers, and a "sometimes working" onscroll event. Unfortunately the "no play()" policy doesn't seem to let a mousewheel scroll count as a user interaction, but I'm working on that too. The thing is, my page is a MUSIC page, literally called "mymusic.html", which you get to following a well labeled MUSIC button. So if ever there was a page to justify 'play 'on load', that one really should! – Randy Jun 15 '19 at 00:00
  • @Randy I am on a very similar situation, I am working on a music page and want to implement autoplay. Adding the autoplay attribute worked very inconsistently - the same code works occasionally, but not always. I have no console or network errors. Did you solve your situation? – Lazarus Rising Mar 14 '20 at 11:38
  • @LazarusRising - While this all seemed to start with phone browsers, I'm noticing newer versions of desktop browsers rejecting autoplay too. I have to say though, I'm satisfied with the need to have an event triggered by user interaction start the music. In fact even I, as the page author, am beginning to find myself annoyed going to my page and having music start just because I touched the screen. I'm starting to see the logic of why auto-play is being phased out. And since its starting to happen universally, I don't feel like my site is the only one that can't do it. – Randy Mar 15 '20 at 21:49
  • 2
    Chrome throws violation for forcing play. – Gabriel Petersson Jul 28 '20 at 11:28
  • 1
    This can be simplified to: `document.addEventListener('click', function() { document.getElementById('ID').play() }, { once: true });` – Henrik N Jul 25 '21 at 11:08
11

Just add this small script as depicted in 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>
Manuel Alves
  • 3,885
  • 2
  • 30
  • 24
  • Can you send me a fiddle for this implementation? It'll be really helpful – Vikash Aug 08 '19 at 21:40
  • 7
    It no longer works? Got this message: "The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio" – thdoan Sep 09 '19 at 05:55
  • 2
    Working on Chrome 81.0.4044.138 on mac – Mosh Feu May 09 '20 at 19:22
5

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 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.

Murtaza JAFARI
  • 674
  • 7
  • 10
5

On adress bar click site settings, or for copy this address (localhost) and select allow on Sound chrome://settings/content/siteDetails?site=https%3A%2F%2Flocalhost

Vitalicus
  • 1,188
  • 13
  • 15
4

You may simply use (.autoplay = true;) as following (tested on Chrome Desktop):

<audio id="audioID" loop> <source src="path/audio.mp3"  type="audio/mp3"></audio>

<script>
var myaudio = document.getElementById("audioID").autoplay = true;
</script>

If you need to add stop/play buttons:

<button onclick="play()" type="button">playbutton</button>
<button onclick="stop()" type="button">stopbutton</button>

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

<script>
var myaudio = document.getElementById("audioID");

function play() { 
return myaudio.play(); 
};

function stop() {
return myaudio.pause(); 
};
</script>

If you want stop/play to be one single button:

<button onclick="PlayStop()" type="button">button</button>


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

<script>
var myaudio = document.getElementById("audioID");

function PlayStop() { 
return myaudio.paused ? myaudio.play() : myaudio.pause();
};
</script>

If you want to display stop/play on the same button:

<button onclick="PlayStop()" type="button">Play</button>


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

<script>
var myaudio = document.getElementById("audioID");

function PlayStop() { 
if (elem.innerText=="Play") {
    elem.innerText = "Stop";
}
else {
    elem.innerText = "Play";
}
return myaudio.paused ? myaudio.play() : myaudio.pause();
};`
</script>

In some browsers audio may doesn't work correctly, so as a trick try adding iframe before your code:

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

<button onclick="PlayStop()" type="button">Play</button>


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

<script>
var myaudio = document.getElementById("audioID");

function button() { 
if (elem.innerText=="Play") {
    elem.innerText = "Stop";
}
else {
    elem.innerText = "Play";
}
return myaudio.paused ? myaudio.play() : myaudio.pause();
};
</script>
Waleed Aldhahi
  • 373
  • 5
  • 4
  • 3
    Doesn't seem to work in Chrome Version 85.0.4183.83 (Official Build) (64-bit) – MC9000 Sep 01 '20 at 00:39
  • 2
    Agree with previous comment. Not working on Chrome 90.0.4430.93 to autoplay just after DOM is loaded, before user interaction. – Jeremie May 07 '21 at 15:55
3

[EDIT @ Sep. 7, 2021]
Just received some downvotes few days ago and I guess I have to make it clear: this solution REQUIRES users to hover their mouse over the webpage to work. There's no way to play sound on chrome without user interaction as it's blocked on purpose. The internet is now filled with intimidating ads and no one wants their browser spamming sounds from ads whenever they visit a website.

[EDIT @ Dec. 22, 2021] I was a clown by spreading misinformation
Turns out some folks didn't grasp an important point of this method. You MUST enclose all parts in the <body> section with a <div>, as states below in the original description. This will NOT work on jsfiddle as it uses an embedded <iframe> document, which is exactly what Chrome is supposed to block.

[EDIT @ Dec. 24, 2021]
Turns out I was a clown. Chrome blocks autoplay whenever users land on a page under a domain different from the last page they visited. Here are some demo I made:

  • If you visit the autoplay demo through this link, it will work properly.
  • However, this direct link will not work as the target domain is different from this very page.

[Original]
If you're OK with enclosing the whole HTML <body> with a <div> tag, here is my solution, which works on Chrome 88.0.4324.104 (the latest version as of Jan., 23, 2021).

First, add the audio section along with a piece of script shown below at the start of <body> section:

<audio id="divAudio">
   <source src="music.mp3" type="audio/mp3">
</audio>

<script>
   var vAudio = document.getElementById("divAudio");
   var hasInit = false;
   function playMusic()
   {
      if(!hasInit)
      {
          hasInit = true;
          vAudio.play();
      }
   }
</script>

Second, enclose your whole HTML <body> contents (excluding the inserted piece of code shown above) with a dummy section <div onmouseover="playMusic()">. If your HTML <body> contents are already enclosed by a global <div> section, then just add the onmouseover="playMusic()" tag in that <div>.

The solution works by triggering the playMusic() function by hovering over the webpage and tricks Chrome of "thinking" that the user has done something to play it. This solution also comes with the benefit that the piece of audio would only be played when the user is browsing that page.

3

Since 2020 this is a browser-related setting and cannot be enabled by html-code. The autoplay is blocked by default on most browsers. Here is where you can find it:

Firefox : where to enable/disable autoplay

Chrome : where to enable/disable autoplay

Mario Favere
  • 490
  • 4
  • 9
0

You could use <iframe src="link/to/file.mp3" allow="autoplay">, if the origin has an autoplay permission. More info here.

Martin van Houte
  • 579
  • 6
  • 24
0

i used pixi.js and pixi-sound.js to achieve the auto play in chrome and 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:

<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.

Akshay Rathod
  • 1,593
  • 3
  • 10
  • 17
0

Use iframe instead:

<iframe id="stream" src="YOUTSOURCEAUDIOORVIDEOHERE" frameborder="0"></iframe>
Rafael
  • 7,605
  • 13
  • 31
  • 46
0

temp fix

$(document).on('click', "#buttonStarter", function(evt)
{
var context = new AudioContext();
document.getElementById('audioPlayer').play();
$("#buttonStarter").hide()
$("#Game").show()
});

Or use a custom player to trigger play http://zohararad.github.io/audio5js/

Note : Autoplay will be renabled in 31 December

0

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!

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.

brooksrelyt
  • 3,925
  • 5
  • 31
  • 54
Puto Miké
  • 73
  • 1
  • 8
0

Solution without using iframe, or 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.

   <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>
Community
  • 1
  • 1
Juan
  • 195
  • 9
0

I thought I would add what I found that will work for our solution. We will be hosting a site in our domain and we can add that site to Chrome's settings to allow auto-play.

I understand why autoplay is usually a little onerous but in this case for our organization it made sense to allow it.

The location in Chrome to allow autoplay by URL is: chrome://settings/content/sound?search=sound

In development with ASP.NET Core MVC, I just added the word: Localhost and that got it working for me (*Note it needs to be added in the Chrome Browser Visual Studio opens automatically).

Jesse
  • 865
  • 10
  • 18
0

In your HTML file <audio src="/path/to/your/music.mp3" autoplay></audio> or this

<audio id="musicplayer" autoplay>
  <source src="/path/to/your/music.mp3" />
</audio>

And in your js file just add this line of code:audioElement.play(); This will play your music! Notice that browsers often provide various forms of autoplay blocking

AzafoCossa
  • 874
  • 8
  • 18
-1

I add controls attribute too tag audio, and simply hide it in CSS. And all works fine in Chrome.

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

The video tag can play audio as well. Given the audio tag doesn't seem to be behaving as it should be, you can just use the video tag for audio:

<video autoplay muted id="audio1" src="your.mp3" type="audio/mp3">
    Your browser does not support the <code>video</code> element.
</video>
<script>
    unmuteButton.addEventListener('click', function() 
        { 
            if ( unmuteButton.innerHTML == "unmute" )
            {
                unmuteButton.innerHTML = "mute";
                audio1.muted = false; 
            } else {
                unmuteButton.innerHTML = "unmute";
                audio1.muted = true; 
            }
        });
</script>
Campbell
  • 62
  • 5
-2

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

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

<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>
Bob
  • 146
  • 9
ItsPronounced
  • 5,475
  • 13
  • 47
  • 86
-2

This little trick worked for me. I used a video tag instead. Auto played the video as muted and set the muted property to false on the window's load event.

<video autoplay loop muted>
    <source src="sample.mp3" />
</video>

<script>
    window.onload = function () {
        document.querySelector("video").muted = false;
    };
</script>
Asher
  • 74
  • 8
-4

The default HTML5 audio autoplay attribute is not working in chrome, but you can force audio autoplay using JavaScript. Try this:

document.getElementById('myAudio').play();

This works for me.

Bob
  • 146
  • 9
  • 4
    it's not that autoplay "doesn't work", it's that it's subject to a policy where the autoplay if will not work if the policy requirements are not met. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes . This code will not circumvent that policy. If it worked for you, it's because you met the threshold and/or set some developer flag. But as that page says, you cannot assume that it will work for everyone. – ADyson Mar 06 '19 at 15:11
  • At least in FF 66, this won't work either. The new policy is to block the play() if it wasn't somehow triggered by a user interaction. – Randy Jun 14 '19 at 23:32
  • Yes @Randy, and the error message in the web browser's console, if we try to play a sound in JS without interacting is: "Error: Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." – Wild8x Nov 27 '20 at 12:38