1.Play audio after page load in JavaScript

Play Audio After Page Load in JavaScript

Introduction

This task focuses on implementing an automated audio playback system using JavaScript. The goal is to trigger audio playback automatically after the webpage has fully loaded. This feature is useful in scenarios where background music or notification sounds enhance user engagement on a website.

Focus Keyword

“Play audio after page load in JavaScript”

Implementation Details

  • An HTML <audio> tag is used to embed the audio file.
  • A JavaScript load event listener is attached to the window object to execute the audio playback when the page finishes loading.
  • To handle modern browser restrictions on autoplay, the script includes a mechanism to gracefully handle errors and provide feedback in the developer console.

Testing

The solution must be tested on multiple browsers (e.g., Chrome, Firefox, Safari) to ensure compatibility and to identify restrictions on autoplay. In some cases, user interaction (like a button click) may be needed to initiate playback.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Play Audio After Page Load</title>
</head>
<body>
    <h2>Play Audio After Page Load in JavaScript</h2>
    <p>Welcome! Background music will play automatically after the page loads.</p>
    
    <audio id="background-audio" src="example-audio.mp3"></audio>

    <script>
        window.addEventListener('load', () => {
            const audioElement = document.getElementById('background-audio');
            audioElement.play()
                .then(() => {
                    console.log("Audio is playing successfully.");
                })
                .catch(error => {
                    console.error("Playback failed or was blocked:", error);
                });
        });
    </script>
</body>
</html>

Output :

  • If the audio starts successfully:
           Audio is playing successfully.
  • If autoplay is blocked by the browser or an error occurs:
           Playback failed or was blocked: <Error Details>

 

Leave a Comment

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

Scroll to Top