Dev.to WebDev 🛠 Dev 👁 0 📖 2 min read

How to Stop Clicks and Pops When Playing Tones With the Web Audio API

If you have ever started an OscillatorNode and heard a sharp click, or stopped one and heard a pop, you have met one of the most common Web Audio annoyances. The fix is simple once you know why it happens. This post expl

If you have ever started an OscillatorNode and heard a sharp click, or stopped one and heard a pop, you have met one of the most common Web Audio annoyances. The fix is simple once you know why it happens. This post explains the cause and shows a small helper that starts and stops tones cleanly.

Why the click happens

A speaker cone follows the waveform you send it. If a sine wave starts at full volume, the signal jumps instantly from silence to whatever value the wave has at that moment. The same thing happens when you call stop() in the middle of a cycle: the signal drops straight to zero. Those instant jumps contain energy across many frequencies, and you hear them as a click. On small phone and laptop speakers the click can be louder than the tone itself.

The fix: short gain ramps

Put a GainNode between the oscillator and the output, start the gain at zero, and ramp it up over a few milliseconds. When stopping, ramp it back down before calling stop().

const ctx = new AudioContext();

function playTone(freq, seconds, volume = 0.3) {
  const osc = ctx.createOscillator();
  const gain = ctx.createGain();
  osc.type = "sine";
  osc.frequency.value = freq;

  const now = ctx.currentTime;
  const fade = 0.02; // 20 ms

  gain.gain.setValueAtTime(0, now);
  gain.gain.linearRampToValueAtTime(volume, now + fade);
  gain.gain.setValueAtTime(volume, now + seconds - fade);
  gain.gain.linearRampToValueAtTime(0, now + seconds);

  osc.connect(gain).connect(ctx.destination);
  osc.start(now);
  osc.stop(now + seconds + 0.01);
  return { osc, gain };
}

Twenty milliseconds is short enough that nobody hears a "fade", but long enough to remove the click on most devices.

Stopping early without a pop

If the user presses a stop button before the tone ends, do not call osc.stop() directly. Keep the object playTone returned, cancel the scheduled ramps and fade out from the current value:

function stopTone({ osc, gain }) {
  const now = ctx.currentTime;
  gain.gain.cancelScheduledValues(now);
  gain.gain.setValueAtTime(gain.gain.value, now);
  gain.gain.linearRampToValueAtTime(0, now + 0.02);
  osc.stop(now + 0.03);
}

setValueAtTime(gain.gain.value, now) pins the current level first, so the ramp starts from where the sound actually is rather than jumping.

Changing frequency smoothly

The same rule applies to pitch. Setting osc.frequency.value directly can cause a small glitch. For sweeps, schedule the change instead:

osc.frequency.setValueAtTime(200, ctx.currentTime);
osc.frequency.exponentialRampToValueAtTime(2000, ctx.currentTime + 5);

Exponential ramps sound even to the ear because pitch is perceived on a logarithmic scale.

Remember autoplay rules

Browsers only allow an AudioContext to make sound after a user gesture. Create or resume the context inside a click handler:

button.addEventListener("click", async () => {
  if (ctx.state === "suspended") await ctx.resume();
  playTone(440, 2);
});

Seeing it in practice

These are exactly the details that matter in browser tools that play test tones, such as this online tone generator, where a click at the start of every tone would be distracting and, on tiny speakers, unpleasant. Add the gain node and the two ramps, and your tones will start and stop cleanly everywhere.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.