DEV Community

Fix My Speaker
Fix My Speaker

Posted on

Generating Test Tones in the Browser with the Web Audio API

You do not need an audio library to play a clean sine wave in the browser. The Web Audio API ships with everything required, and a working tone generator fits in about twenty lines. Here is a minimal version and the gotchas I hit along the way.

The minimal tone

let ctx, osc, gain;

function startTone(freq = 440, volume = 0.2) {
  ctx = ctx || new AudioContext();
  osc = ctx.createOscillator();
  gain = ctx.createGain();

  osc.type = 'sine';
  osc.frequency.value = freq;
  gain.gain.value = volume;

  osc.connect(gain).connect(ctx.destination);
  osc.start();
}

function stopTone() {
  // ramp down to avoid a click
  gain.gain.setTargetAtTime(0, ctx.currentTime, 0.02);
  osc.stop(ctx.currentTime + 0.1);
}
Enter fullscreen mode Exit fullscreen mode

Wire startTone() to a button click and you have a tone.

Gotcha 1: autoplay policy

Browsers will not start an AudioContext without a user gesture. Create or resume() the context inside a click or keypress handler, otherwise it stays in the suspended state and you get silence with no error.

Gotcha 2: clicks and pops

Starting or stopping a waveform abruptly at a non-zero point produces an audible click. Ramp the gain instead of cutting it: setTargetAtTime or linearRampToValueAtTime over 10 to 30 ms is enough.

Gotcha 3: oscillators are single use

An OscillatorNode can only be started once. To play again, create a new oscillator. Keep the AudioContext and reuse it; creating many contexts is wasteful and some browsers cap the number.

Gotcha 4: protect your users' ears and speakers

Default the volume low (0.1 to 0.2), and be careful with very low and very high frequencies at full gain. Small phone speakers can rattle hard below about 100 Hz, and tones above 15 kHz may be inaudible to some users while still being loud.

Sweeps

A frequency sweep is just a ramp on frequency:

osc.frequency.setValueAtTime(20, ctx.currentTime);
osc.frequency.exponentialRampToValueAtTime(20000, ctx.currentTime + 10);
Enter fullscreen mode Exit fullscreen mode

Use an exponential ramp: our hearing is logarithmic, so a linear ramp spends almost all its time in the treble.

Seeing it in practice

If you want to compare your implementation with a finished one, this online tone generator does exactly this in the browser, with adjustable frequency and waveform. It is handy for checking speakers, testing hearing range, or debugging your own audio code against a known reference.

The Web Audio API is one of the more pleasant browser APIs once you know these four rules. Have you built anything fun with it?

Top comments (0)