How to play an automatic sound when loading a web page?

To play a sound directly, as the page loads, you have to meet a series of conditions.

The simplest is that the user has previously interacted with the page. This is, for example, that you have made a simple click on any element on the page. At that moment (in which you know for sure that the user has clicked) you can already present the sound with the autoplay.

To explain myself better, previously it was enough to put a sound tag like this:

But as I say, if that tag appears before the user has interacted with the page, it just won’t start the sound and it’s useless. Even if you interact later, as the tag was already present, it is not possible to get autoplay.

The solution is to make sure that tag appears on the page right after the user has clicked anywhere in the document. You can achieve this with Javascript, with a code like this:

const playSound = function() { let element = document.createElement(‘div’); element.setAttribute(‘style’, ‘display: none’); element.innerHTML = `

Another alternative that can reduce your Javascript code is that you already have the audio tag on the page, without the autoplay and that you play it with Javascript when the document is clicked.

sound2

Finally, there would be the alternative of using the Javascript Audio class. But this code would not produce a looping sound, starting again when finished. In addition, it is not possible to deliver as several audio files so that the browser chooses the one that is compatible with it.

See also  web performance analysis tool

const playSound = function() { var sound = new Audio(“audio-file.mp3”); sound.play(); document.removeEventListener(‘click’, playSound); } document.addEventListener(‘click’, playSound);

I have seen that they comment on another alternative that uses an iframe, but the truth is that I have not been able to make it work. The issue may simply be that Google Chrome changes its sound or video autoplay policies and makes them more and more restrictive, so what works at one time may not work later.

At the moment, the safest thing, and it seems that it will not change, would simply be to make sure that the user has interacted with the page, to later play the sound that you need.

Loading Facebook Comments ...
Loading Disqus Comments ...