When this happens on Google Chrome, the error is currently showing a link to this page: https://developer.chrome.com/blog/autoplay/.
As the post explains, Google Chrome keeps track of an individual's propensity to consume media on a site, using a metric called MEI (Media Engagement Index).
Based on that metric, an attempt to play sound on page load may or may not work. You can see a list of the scores of which Chrome keeps track by going to chrome://media-engagement/
on your browser.
To handle cases in which the play on page load doesn't work, the post suggests the following code snippet:
var promise = document.querySelector('video').play();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
In your case it could be:
const playAudio = $("#sound")[0];
const promise = playAudio.play();
let playedOnLoad;
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
playedOnLoad = true;
}).catch(error => {
// Autoplay was prevented.
playedOnLoad = true;
});
}
At this point you can use the playedOnLoad
value to show a button or add a listener to some other types of user interaction.
Another option (the one I'm adopting) is to always show a toggle for the sound, and to change it's state (play/stop or enable/disable) based on the result of the promise.
Please remember that the MEI score is also saved for your local development environment, so, based on your personal interaction with the page, the sound may or may not start on page load even in your local environment.