How to make audio autoplay on chrome
Solution 1
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.
Solution 2
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.
Solution 3
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
Solution 4
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>
Solution 5
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..
Akshay Rathod
Updated on December 25, 2021Comments
-
Akshay Rathod over 2 years
Audio autoplay is 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?
-
Akshay Rathod about 6 yearsit is showing controls and i don't want anything on the page. just play and pause button.
-
Akshay Rathod about 6 yearsi want audio to play in background.
-
Akshay Rathod about 6 yearsso you are saying there not way we can autoplay the audio in chrome browser?
-
Akshay Rathod about 6 yearsand how to loop the audio?
-
Kwarrtz almost 6 yearsHow do you make the audio loop?
-
Neil Bryson almost 6 yearsOK, 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 almost 6 yearsSlightly off topic, but your silence.mp3 is quite large at 36.7k. Try this (216 bytes) - s3-eu-west-1.amazonaws.com/neilbryson.net.random/silence.mp3
-
Ignacio Segura over 5 yearsSolution 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.
-
idbrii over 5 yearssilence.mp3 link is dead. You can create your own.
-
Travis over 5 yearsThe link to the silence file is dead, so I found some other silence files on GitHub: 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. -
ADyson over 5 yearsit'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 developers.google.com/web/updates/2017/09/… . 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.
-
Anvesh Reddy over 5 years@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();
-
Toniq about 5 yearsInteresting, I wonder why this method does not work for video as well?
-
Toniq about 5 years@Neil Bryson - Can you re upload silence 216 bytes mp3 file?
-
Neil Bryson about 5 years@Toniq Of course, apologies all - s3-eu-west-1.amazonaws.com/omegasquadron.neilbryson.net/…
-
hmd about 5 years@AkshayRathod please check HTML <audio> loop Attribute. Whereas, In XHTML, attribute minimization is forbidden, and the loop attribute must be defined as <audio loop="loop">.
-
Randy about 5 yearsAt 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 about 5 yearsThis 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!
-
mightyiam about 5 yearsRelying on a user interaction is not autoplay.
-
mightyiam about 5 yearsMuted audio autoplay can't be considered an answer.
-
mightyiam about 5 yearsPerhaps if your MEI for that site allows autoplay. Otherwise, I don't see a reason that this would work.
-
mightyiam about 5 yearsThis is not an answer, because it's not autoplay.
-
Youssef KH almost 5 years@mightyiam this is a workaround since there is no way to autoplay since chrome blocked it
-
mightyiam almost 5 yearsSeems busted as of Chrome 76.
-
Yulian almost 5 yearsYeah, this doesn't work anymore (if it did work in the past)
-
Vikash almost 5 yearsCan you send me a fiddle for this implementation? It'll be really helpful
-
zeta almost 5 yearsAlso, there is a permissions option in Chrome Browser in Android now that the user can select to allow sounds in autoplay
-
Praditha almost 5 yearsI 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.
-
thdoan almost 5 yearsIt 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. developers.google.com/web/updates/2017/09/…"
-
The Dead Man almost 5 years@Akshay Rathod did u find solutions?
-
Veer3383 over 4 years@LeonardStorcks it was working for me 2 months ago, but it stopped working the moment i went to https
-
Lazarus Rising over 4 years@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?
-
Randy over 4 years@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.
-
Mosh Feu about 4 yearsWorking on Chrome 81.0.4044.138 on mac 👍
-
Stefan Reich about 4 yearsYeah they're on to it... doesn't work anymore in either Firefox or Chrome
-
Gabriel Petersson almost 4 yearsChrome throws violation for forcing play.
-
MC9000 almost 4 yearsDoesn't seem to work in Chrome Version 85.0.4183.83 (Official Build) (64-bit)
-
MC9000 almost 4 yearsNope. Does not work in Chrome Version 85.0.4183.83 (Official Build) (64-bit)
-
Wild8x over 3 yearsYes @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."
-
Jeremie about 3 yearsAgree with previous comment. Not working on Chrome 90.0.4430.93
-
Jeremie about 3 yearsAgree with previous comment. Not working on Chrome 90.0.4430.93 to autoplay just after DOM is loaded, before user interaction.
-
Smooth Neon almost 3 yearsit works but it's very limited when it comes to divs with various sizes
-
Matstar almost 3 yearsThis can be simplified to:
document.addEventListener('click', function() { document.getElementById('ID').play() }, { once: true });
-
showdev almost 3 yearsSounds like this answer might "now pose security risks or provide code that no longer works".
-
showdev almost 3 yearsSounds like this answer might "now pose security risks or provide code that no longer works".
-
vhiefa over 2 yearsit works but once the user click "stop" button on music control, then continue mouseiver again, this will play again. very annoying. Any solution???
-
Zevin Zenph Zambori over 2 years@vhiefa I guess you may add a flag using
var hasInit = false;
along with a check in theplayMusic()
function, such that the instructionvAudio.play();
only executes once. I'll update my post. -
TiberiumFusion over 2 yearsDoes not work in Chromium 96.0.4664.93. See jsfiddle here: jsfiddle.net/j9k75bhe Open the fiddle, do not click on anything on the page, then move the mouse around the red area. No audio will play. Check the browser console and you will see a nice message from Google telling you it blocked the audio from playing. Moving the mouse across the page does not satisfy Google. The user must actually click somewhere on the page before any audio can be played.
-
Zevin Zenph Zambori over 2 years@TiberiumFusion it still works for me using single file HTML. If you check it carefully the console says it's a
DOMException
. It's an ad-blocking feature that blocks annoying ads you may see on the corner of many news pages. You have to enclose your whole HTML body for this to work, as stated clearly in the solution. -
TiberiumFusion over 2 years@ZevinZenphZambori I recommend you post a complete working example of your concept. If we take the jsfiddle I shared and remove jsfiddle from it, we end up with a very basic page like this. No iframes, just barenaked html. Test it out, and Chromezilla still dutifully blocks audio playback. You may want to check your
chrome://media-engagement/
and ensure that you do not have a "high" MEI for the domain you are testing with and receiving the intended results on. -
Zevin Zenph Zambori over 2 years@TiberiumFusion Turns out I was a clown. Chrome now blocks autoplay if the users are visiting a new domain. I made some demo here: an entry page that links users to a page under same domain that triggers autoplay successfully index.html, and a link that send users directly to this new domain that autoplay would be blocked.
-
57ar7up over 2 years@ZevinZenphZambori I replicating your code with Node.js / Express and can't play audio even when redirected from same domain. I already want to kill Google (and Mozilla too)
-
57ar7up over 2 yearsOh, on Chrome Android it working, how nice
-
Zevin Zenph Zambori over 2 years@57ar7up Have you tried my demo linked in the post? It works fine in latest Chrome 97.0.4692.71 on Windows for me. Also it's supposed to work like this and it really helps controlling the horribly degenerated ads placements on many websites. No one likes those auto-playing ads videos on a news website bombarding them with auto-playing sounds.
-
57ar7up over 2 years@ZevinZenphZambori yes, now even simple <audio autoplay> working without giving explicit site permission to localhost, don't know why it wasn't worked before. But still, it not working without redirect from same domain, and sites like YouTube, Facebook, VK somehow do this right
-
Zevin Zenph Zambori over 2 years@57ar7up I indeed cannot find a working snippet without redirecting from the same domain. I found the proposed solution when I was setting up a private project which turned out only requires autoplay after same-domain interaction. I'm not sure how YouTube or Facebook implement theirs and I even suspect there is some sort of hard-coded whitelist.
-
Alec Jacobson about 2 yearsThis doesn't appear to work (anymore?)
-
Alec Jacobson about 2 yearsIIUC, this not only requires that the user mouseovers but that they have clicked (on this page or on one of the same domain).
-
Murtaza Hussain about 2 years@AlecJacobson did you test it ? does it not work anymore ?
-
Oli Crt about 2 yearsworks only by adding
allow="autoplay"
for me