'Is there any working way to autoplay audio on all major browsers using Javascript?
I have set up some HTML & Javascript that can control the playing of an audio track on a webpage, I really like simplicity of JavaScript with play/stop function but I can't make it play automatically. Here's my javascript code:
$('body');
var audio = document.getElementById("audio-player");
audio.volume = 0.2;
if ($(window).length) {
$('.bg-player').css({
'visibility': 'visible'
});
$('body').addClass("audio-on");
if ($('body').hasClass('audio-on')) {
$('body').removeClass('audio-off');
}
$(".bg-player").on('click', function() {
$('body').toggleClass("audio-on audio-off");
if ($('body').hasClass('audio-off')) {
audio.pause();
}
if ($('body').hasClass('audio-on')) {
audio.play();
}
});
}
I tried to add the autoplay property but no success:
audio.autoplay = true;
I would like know if there is a way for play the file on the page load.
Solution 1:[1]
It's a browser security feature to not autoplay an audio unless there is some user interaction.
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#new-behaviors
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 played video with sound. The user has added the site to their home screen on mobile or installed the PWA on desktop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saren |
