Play audio after page load in JavaScript

When you’re thinking about adding some audio to your website, like having music or sound effects play as soon as the page loads, it can be a nice way to make your site more engaging. Whether it’s background music to set the mood or a notification sound to alert users to something important, audio can enhance the experience. However, it’s important to use this feature thoughtfully.

So, in this tutorial, we will learn how to play audio after the page loads in JavaScript.

 

How to Automatically Play Audio After Page Load in JavaScript

To play an audio file automatically after a page loads using JavaScript, you can follow these steps:

  1. Create the Audio Object: Use JavaScript to create an audio object with the new Audio() function. This function links to the audio file you want to play.
    var audio = new Audio('path/to/your-audio-file.mp3');

    The above code sets up the audio file so that it is ready to be played.

  2. Setting Up the Event Listener: Next, you need to make sure that the audio file starts playing once the page has fully loaded. This can be done by using the window.onload event. This event triggers a function when everything on the page has loaded, including images and scripts. Inside this function, you call audio.play() to start playing the audio.

So, our final code looks like this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> My Audio</title>
</head>
<body>

    <script>
        // Create an audio object and link it to our audio file
        var audio = new Audio('path/to/your-audio-file.mp3');
        
        // When the page finishes loading, start playing the audio
        window.onload = function() {
            audio.play();
        };
    </script>

</body>
</html>

This code ensures the audio starts automatically after the page loads, and the comments help clarify each part of the process.

 

NOTE :

It’s important to note that some modern browsers have restrictions on auto-playing audio or video content unless the user interacts with the page first. This is done to prevent unexpected sounds. If your audio doesn’t play automatically, you might need to prompt the user to click something before it starts. So, be aware of these browser restrictions.

Leave a Comment

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

Scroll to Top