0

I have a gaming website and I'm using this following audio element to automatically play a one-two seconds long audio in the background on certain pages after they are loaded:

<audio autoplay hidden>
<source src="gallery/Welcome.MP3" />
</audio>

It works, but only if I actually click on the menu to load the page. If I type the website/webpage in the browser, or use a direct link, it never plays. Can someone tell me why it is and how I can make it play in all cases?

Gab
  • 1
  • 2
  • 1
    The short answer is you can’t, the long answer is you can’t and you shouldn’t. Have a check of the html and audio tags for autoplay and you’ll see the reasons why, the most recent is https://stackoverflow.com/questions/65567126/html-js-play-audio-file-on-page-load/65568009?r=SearchResults#65568009 – fdcpp Jan 10 '21 at 08:17
  • Thank you! This is very useful. I guess I just accept it then. – Gab Jan 11 '21 at 07:31

1 Answers1

0

Use <audio src="gallery/Welcome.MP3" autoplay></audio>

OR

According to this answer. You can use:

<audio id="my_audio" src="gallery/Welcome.MP3"></audio>

<script>
window.onload = function() {
document.getElementById("my_audio").play();
}</script>
m24197
  • 1,038
  • 1
  • 4
  • 12