Explain Codes LogoExplain Codes Logo

How to play a notification sound on websites?

javascript
prompt-engineering
audio-engineering
browser-compatibility
Anton ShumikhinbyAnton Shumikhin·Dec 27, 2024
TLDR

Got a minute? Here is the bento box solution. Use <audio> and JavaScript to trigger a sound:

<audio id="notif" src="notify.mp3"></audio> <button onclick="document.getElementById('notif').play()">Play Sound</button>

Just replace "notify.mp3" with the path to your audio file. Hit that button and Bob's your uncle, you've got your sound!

In-depth explanation

Hold tight. We are going to dive deep into notification sound implementation ensuring broadest browser compatibility and top-notch user experience.

Covering all bases: Cross-browser audio compatibility

Just like a dating app success, you want to appeal to as many (browsers) as you can. So, make sure to offer multiple audio formats:

function playSound(soundfile) { var audioElement = document.createElement('audio'); audioElement.setAttribute('src', soundfile + '.mp3'); // Flashy and modern audioElement.setAttribute('ogg', soundfile + '.ogg'); // The hipster alternative audioElement.play(); }

Catering vintage browsers

If your <audio> doesn't charm every browser, do a fallback with the <embed> tag:

function playLegacySound(soundfile) { if (document.createElement('audio').canPlayType) { // If the browser is cool var audioElement = new Audio(soundfile + '.mp3'); audioElement.play(); } else { // When dealing with browser veterans document.write('<embed src="' + soundfile + '.mp3" hidden="true" autostart="true" loop="false" />'); } }

Preloading and volume control

Ever been at a gig that starts too loud? Avoid that with volume control. Plus, with sound preloading, your sound is as ready as a coiled spring:

var audioElement = new Audio(); audioElement.src = 'notification.mp3'; audioElement.volume = 0.5; // Half the volume, double the fun audioElement.preload = 'auto'; function triggerNotification() { audioElement.play(); // Play the sound when the occasion arises }

Be a good guest: On-demand initiation

Nobody likes unannounced visitors. The same goes for sound. Initiate playback via user interactions or specific events:

document.getElementById('messageButton').addEventListener('click', function() { audioElement.play(); // Like a butler, only plays when asked to }, false);

User experience: Handle with care

Lastly, remember usability. Give the user control over the sound, because uncontrolled audio can ruin an otherwise great page.

Advanced topics and considerations

Use a little help from the libraries

Working with raw JavaScript is fun, yet Ion.Sound can make things way easier, and it's independent:

// Calling Ion.Sound to duty ion.sound({ sounds: [{name: "notification"}], path: "path/to/sounds/", preload: true, volume: 0.5 }); // Play the sound when needed ion.sound.play("notification");

Upgrading embedding: Dynamic JavaScript

The <audio> element can be created dynamically with JavaScript:

function createAudioElement(soundfile) { var newAudio = document.createElement('audio'); newAudio.src = soundfile; document.body.appendChild(newAudio); return newAudio; } var myNotificationSound = createAudioElement('notification.mp3'); myNotificationSound.play(); // When the time is right, play the sound

Sneak-a-peek: Invisible audio

Always dreamed of being a sound ninja? Use the JavaScript Audio object to introduce notification sounds with no visible footprint:

var audio = new Audio('notification.mp3'); window.addEventListener('event', function() { audio.play(); // Silent but lethal });