How to play a notification sound on websites with JavaScript?

Spread the love

Sometimes, we want to play a notification sound on websites with JavaScript.

In this article, we’ll look at how to play a notification sound on websites with JavaScript.

How to play a notification sound on websites with JavaScript?

To play a notification sound on websites with JavaScript, we use the Audio constructor.

For instance, we write

<button onclick="playSound('https://your-file.mp3');">Play</button>

to add a button that calls the playSound function when we click it.

Then we write

function playSound(url) {
  const audio = new Audio(url);
  audio.play();
}

to define the playSound function that passes the url into the Audio constructor.

Then we call play to play the audio clip at the url.

Conclusion

To play a notification sound on websites with JavaScript, we use the Audio constructor.

Leave a Reply

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