How to Play Audio After The Page Loads in HTML With JavaScript

By Saruque Ahamed Mollick

Hello developer, today I am going to show you how to play audio after page load in JavaScript. In many cases, it is seen that we need to play the audio file only after the webpage gets loaded. Because most of the times, we don’t wanna play the audio file before the webpage getting loaded.

Bottom Sticky Music Player Source Code in JavaScript and CSS

 



You should also learn How to Play Audio After Few Seconds or Delay in JavaScript

Play this video tutorial to learn more

 

Play Audio After The Page Loads in JavaScript

So before showing you that directly I would like to show you how audio file is played in HTML.

<!DOCTYPE html>
<html>
<head>
  <title>My Audio</title>

</head>
<body>
  <audio src="mysong.mp3" id="my_audio" loop="loop" autoplay="autoplay"></audio>
</body>
</html>

So we need to remove the autoplay attribute first. Then we gonna add our JavaScript function to play the audio on page load.

<script type="text/javascript">
window.onload=function(){
    document.getElementById("my_audio").play();
  }
</script>

So our full code will look like this

<!DOCTYPE html>
<html>
<head>
  <title>My Audio</title>

</head>
<body>
  <audio src="mysong.mp3" id="my_audio" loop="loop"></audio>
  <script type="text/javascript">
    window.onload=function(){
      document.getElementById("my_audio").play();
    }
  </script>
</body>
</html>
window.onload

will run this function after page load.

 document.getElementById("my_audio").play();

Here document.getElementById() method is responsible for getting the audio file by its id.

Later, play() method is used to play the audio file.

Also Read,

How To Get Selected Option from HTML Form Dropdown in jQuery

HTML5 Video/Audio player Volume Control With Key in JavaScript

Special Note:  The audio tag is used in the body tag not in the head tag, because if you insert it into the head tag the browser will automatically load the media data in the body section. You can use your browser’s inspect option to see what happens if you put the audio tag in the head tag.

So it’s better to put the audio tag in the body tag.

Using this JavaScript function you can easily play the audio file after page loading.

Feel free to write in the comment section and watch the video embedded on this page to learn how to set the time delay to play your audio file on the webpage.

Leave a Reply

Your email address will not be published. Required fields are marked *