i am using this code and when i see the controls
i see the autoplay is not working.
There is no way to get autoplay working in mobile browsers. (This is not allowed)
But some tricks do this thing.
Click on the links below to view some tricks
Autoplay audio on mobile safari
iOS-Specific Considerations | Loop Attribute
Now, it's2020
Note that (for the below reason?) Chrome has changed their autoplay policy (see https://developers.google.com/web/updates/2017/09/autoplay-policy-changes ) so you now must either:
resume()
the audio context after some (any) user interaction with the pageYou can play a sound using the AudioContext API and taking the source from any ArrayBuffer
(ie: from a XMLHttpRequest
or a File
)
window.addEventListener('load', function () {
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var source = audioCtx.createBufferSource();
var xhr = new XMLHttpRequest();
xhr.open('GET', 'audio-autoplay.wav');
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function (r) {
audioCtx.decodeAudioData(
xhr.response,
function (buffer) {
source.buffer = buffer;
source.connect(audioCtx.destination);
source.loop = false;
});
source.start(0);
});
xhr.send();
});
Live example
Works on Chrome and Firefox both mobile and Desktop
Important notes
It's worth mentioning, IMO, that this "trick" can actually be considered as a browser bug, and might no longer work at any time if browser decide that this breaks user experience/becomes a widely-used annoyance (like ads).
It's also worth mentioning that, at least on my mobile and FF 54, the sound will still be played, even if your mobile is muted...
It's also also worth mentionning that user might set the autoplay
behavior to fit their wishes and needs either through the browser's usual options or through the more-advanced about:config
page (autoplay
behavior is set by Firefox's media.autoplay.enabled
and media.block-autoplay-until-in-foreground
preferences).
So forcing the audio autoplay
is a bad UX idea no matter how you do it.
I have a lot of experience with this problem. It also applies to Javascript audio that loads before the user has had a chance to interact with the page.
HOWEVER, once a user clicks absolutely anything, it's game on. I personally recommend a full-page entrance overlay right on the front page: "Click to enter my awesome site!" If the user enters the page at all, they are doomed to hear whatever sounds you want to throw at them! :D