JavaScript Answers

How to play a notification sound on websites with JavaScript?

Spread the love

To play a notification sound on a website using JavaScript, you can use the HTML5 Audio element.

For example, we write:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notification Sound</title>
    <button onclick="playNotification()">Play Notification Sound</button>

        function playNotification() {
            var audio = new Audio('notification.mp3'); // Replace 'notification.mp3' with the path to your audio file

In this example, we have a button with an onclick attribute that calls the playNotification() function when clicked.

Inside the playNotification() function, we create a new Audio object and pass the path to the audio file (e.g., 'notification.mp3') as an argument.

Then, we call the play() method on the audio object to play the sound.

Make sure to replace 'notification.mp3' with the actual path to your audio file. You can use different audio formats like .mp3, .ogg, or .wav, depending on browser support and your preference.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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