How to play audio after the page load in JavaScript

Play audio on page load in JavaScript

To play audio in JavaScript Audio() constructor can be used, which is an alternative to the <audio> element in html and can be used to directly link an audio file with a variable in JavaScript.

Step 1 : 

Make a constant Object of Audio constructor, and input the file location of the audio file as given.

const audio = new Audio("audio/sounds.mp3");

 

Step 2 :

Write the code in js file :

const audio = new Audio("audio/sound.mp3");

window.onload = () =>{
    audio.play();
}

Explanation :

  • To play the audio, play() can be used on audio constant
    audio.play();
  • Use window.onload EventHandler to play the audio when the page is loaded
    window.onload = () =>{
        audio.play();
    }

    Here, window.onload will execute the anonymous function when the page is loaded.

Chrome may not allow to play audio

 

 

Leave a Comment

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

Scroll to Top