We can play a notification sound on websites with JavaScript by creating an audio player object with the Audio
constructor.
For instance, if we have the following button:
<button>Play</button>
Then we can use the Audio
constructor to play an audio clip when we click it by writing:
const playSound = (url) => {
const audio = new Audio(url);
audio.play();
}
const button = document.querySelector('button')
button.addEventListener('click', () => {
playSound('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
})
We create the playSound
function that takes the audio url
.
And we pass the url
into the Audio
constructor to create the audio player object.
Next, we call play
to play the audio file at the given url
.
Then we get the button with document.querySelector
.
And then we call addEventListener
to add a click listener to the button.
In the event handler callback, we call playSound
with the URL of the audio file we want to play.
Now when we click the button, the audio at the given URL should play.
Conclusion
We can play a notification sound on websites with JavaScript by creating an audio player object with the Audio
constructor.