Explain Codes LogoExplain Codes Logo

How do I make JavaScript beep?

javascript
web-audio-api
data-uri
cross-browser-compatibility
Nikita BarsukovbyNikita Barsukov·Jan 11, 2025
TLDR

Quickly add beep in JavaScript with this function using the Web Audio API.

We create an oscillator to emit a pure frequency:

function beep(freq) { const ctx = new (window.AudioContext || window.webkitAudioContext)(); let osc = ctx.createOscillator(); osc.connect(ctx.destination); osc.frequency.value = freq; osc.type = 'sine'; osc.start(); osc.stop(ctx.currentTime + 0.2); } // Usage: beep(520); // 520Hz tone for 0.2 seconds, "Hello there, frequency!"

Invoke beep() with the desired frequency. The above example plays a 520Hz tone—a typical beep sound—for a short, non-intrusive duration.

Get creative with additional options

Developing a sound environment in JavaScript benefits from knowing the following aspects for practical and user-friendly implementation.

Portable sound with data URIs

Embed your sound directly in your JavaScript file by using base64-encoded sound in Data URIs. This approach is perfect for standalone applications or when you need a self-contained feature.

Balance beep and user experience

A beep can enhance user interactions, but don't let it become a nuisance. Enable user control over sound playback, including a mute option.

Beep under every browser's hood

Ensure that your beep is browser-agnostic by checking cross-browser compatibility. Consider implementing a fallback using a Data URI in an <audio> tag for the ol' browser folks.

Mastering the volume

Not too loud, not too quiet; have the beep sound just right. The Web Audio API's createGain() method enables detailed volume controls.

Dynamic beeps for dynamic folks

Customizable duration, frequency, and volume for the beep works wonders in different contexts and settings.

Implementing beeps in the field

Now let's explore practical applications like using beep-to-inform functionality within user interface dynamics.

Textarea character limit alert

Let's say you want to alert the user with a beep when they are near the maximum character limit in a textarea:

const textarea = document.querySelector('textarea'); const maxChars = 100; textarea.oninput = () => { if (textarea.value.length > maxChars) { beep(520); // "Beep: consider this a gentle nudge!" } };

Different beeps for unique events

Beeps can be personalized for unique user interactions. Customize beeps for different actions such as success or error notifications:

function successBeep() { beep(880); // "It's a win! Let's have a cheer!" } function errorBeep() { beep(220); // "Error: now that hits a low note!" }

Test on mobile too, beep-beep on the move!

To ensure a well-rounded experience, verify the beep operation on mobile platforms, as they might render sound differently.