Radio from scratch · Chapter 19
Cleaner sound
By chapter 11 the radio made sound. This chapter is about making that sound pleasant to listen to for an hour: a police dispatcher without the hum underneath, a weak voice without the hiss on top, pauses that stay quiet, peaks that don't crackle, and a stream that never stutters. Every piece is a row of controls under Spectrum Lab's waterfall, and every piece is under a hundred lines.
The question to keep in mind: how can you remove hiss from a voice when the hiss and the voice are at the same frequencies?
A filter for voices
Narrow FM, AM and SSB carry speech, and speech lives between about 300 and 3000 Hz. Below it, many repeaters (relay stations on hills and towers that rebroadcast handheld radios) add a quiet CTCSS tone, 67 to 250 Hz, that opens other radios' squelch: you hear it as a hum. Above it is mostly hiss. So the first cleanup is a band-pass (a filter that keeps only a band in the middle): cut below 300 Hz, cut above 3000 Hz.
Why not use chapter 6's FIR filter here? Because at 48 000 audio samples a second, a 100 Hz hum is a very slow wave (480 samples per turn), so cutting sharply at 300 Hz with chapter 6's sliding average would take hundreds of weights — hundreds of multiplications per sample. For audio there's a much cheaper kind of filter that needs only five multiplications, because it keeps memory of its own output: each new output sample mixes the last two inputs and the last two outputs. Feed it a single click and watch it answer:
Five numbers do it all, and it's called a biquad. Because it feeds its output back in, the answer to one click rings on for a while, as if it were a long filter, yet it only ever does five multiplications. The recipe for the five numbers (from Robert Bristow-Johnson's "audio EQ cookbook", the one almost every audio program uses) turns a cutoff frequency into coefficients. Two of them in a row, a 300 Hz high-pass and a 3 kHz low-pass, make the voice filter:
Measured by the chapter's script: the lowest CTCSS tone, 67 Hz, comes out 26 dB quieter; 1000 Hz is untouched (−0.1 dB); hiss at 8 kHz is 19 dB down. At exactly the cutoffs the level is −3 dB: half the power, which is how a cutoff is defined. Spectrum Lab skips the filter in WFM, where music needs the whole 15 kHz.
- The names: x[n] is input sample n and y[n] output sample n; the b's weigh the newest inputs and the a's the last two outputs. ω (omega) is the cutoff fc written as an angle per sample. Q sets the shape of the corner at the cutoff: 1/√2 is the flattest, higher values add a bump. α (alpha) is just a helper made from ω and Q.
- Every coefficient is then divided by 1 + α. Q = 1/√2 gives the flattest passband (a Butterworth filter). The high-pass uses (1 + cos ω)/2 and −(1 + cos ω) for the b's.
- The a's are the memory of the output. They make it cheap, and they're also why a badly designed one can ring forever (an unstable filter). The cookbook's recipe is always stable.
Hiss and voice at the same frequencies
Now the hard question from the top. Hiss covers every frequency, including 300–3000 Hz, so no fixed filter can remove it without removing the voice. But hiss and voice behave differently over time. A voice is loud at a few frequencies for a few hundredths of a second, then moves; hiss is the same faint level everywhere, all the time. So look at the sound in short slices, and in each slice turn down only the frequencies that are no louder than the hiss.
Slicing sound into frames and putting it back together without seams is a trick of its own. Each frame is 512 samples (about 11 ms), the frames overlap by half, and each is shaped by a window, applied twice: once going in, once coming out:
The window is the square root of chapter 4's Hann window. Applied twice, it becomes a Hann window, and Hann windows placed half a frame apart add up to exactly 1 everywhere (the script checks: to within 0.00000007). So if nothing is changed in between, the sound comes back exactly as it went in, just one frame late. Whatever we change in a frame fades smoothly into its neighbors, so there are no clicks at frame edges.
- This is called overlap-add: window, FFT, change, inverse FFT (chapter 4: the arrows added back up), window again, add into the output. It's how almost every audio effect that works on frequencies is built.
Turning down what sounds like hiss
Inside one frame we have the FFT: a level for every frequency bin. Suppose we already know the hiss level in each bin (next section). Then a bin much louder than the hiss is mostly voice: keep it. A bin about as loud as the hiss is mostly hiss: turn it down. That rule, a gain per bin, is the whole noise reducer:
Push it too hard and something strange happens. Hiss isn't perfectly even: in each frame, a few bins happen to poke above the estimate, so their gain flips up to 1 for 11 ms, then back down. Scattered all over the spectrum, those flickers sound like warbling little tones, a watery, robotic effect called musical noise. Watch the gains of every bin over time, with and without the two fixes:
The fixes are both about being gentle. A floor: never turn a bin down by more than 20 dB, so the hiss that's left is a soft, steady bed instead of silence with sparkles. And smoothing: a gain may rise quickly (so the start of a word isn't cut) but falls back only gradually. Spectrum Lab's strength slider moves both at once: from subtracting half the hiss with a −6 dB floor, to twice the hiss with a −20 dB floor.
A voice can be cleaned frequency by frequency: in short overlapping frames, turn down each bin that's no louder than the hiss learned in the pauses, gently enough that nothing warbles.
Why do the overlapping windows add back to exactly 1?
- The window used twice is a Hann window: w(n) = ½ − ½ · cos(2πn / N).
- The next frame starts half a frame later, where the cosine is half a turn further on.
- Half a turn flips a cosine's sign: that frame's window at the same moment is ½ + ½ · cos(2πn / N).
- Added: ½ − ½ cos + ½ + ½ cos = 1, at every moment.
- So frames left untouched rebuild the sound exactly, and changed frames blend smoothly into each other.
Where it breaks
The noise tracker can't tell a steady tone from hiss. It rises about 8 dB a second whenever a bin's level doesn't dip, so a whistle 20 dB above the hiss looks like hiss after about 20 ÷ 8 = 2.5 seconds, and gets turned down. Speech is safe because it keeps pausing. For a steady whistle, chapter 18's filter shift is the right tool.
- Sk: bin k's power (smoothed over a few frames); Nk: its hiss level; β (beta): how much hiss to subtract (0.5 to 2); G̃k: the gain actually used.
- The same gain is applied to bin k and its mirror image (bin N − k), so the output stays real sound.
Learning the hiss while someone talks
We needed each bin's hiss level, but nobody tells us when the voice is silent. The trick: the hiss is the level a bin keeps falling back to. Track each bin's level in decibels with a line that falls toward every dip (a twentieth of the way each frame) and rises slowly otherwise, about 8 dB a second:
During a word the bin's level jumps up, but the tracker only creeps after it; between words the level drops back and the tracker follows it down. If the hiss itself gets louder (you tuned to a noisier channel), the tracker climbs to it in a second or two. One correction: a line that lives in the dips sits below the hiss's average, by a factor of about 2.2 in power (measured, for this exact tracker). So the estimate is the tracker times 2. The script's result: with strength 1, the hiss in pauses drops by 11.5 dB, while a tone keyed on and off like speech changes by 0.2 dB.
- Raising a ratio to the power 0.05 is moving a twentieth of the way in decibels. 1.01 per frame, at 187 frames a second, is +8 dB a second.
A steady, unchanging whistle sits in the passband for a minute. What does the noise reducer do to it?
- Slowly decides it's hiss and turns it down
- Leaves it alone, because it's loud
Quiet pauses: AGC hang
Chapter 11's automatic volume follows the loudest recent peak and slowly turns up when things get quiet (↩). That slow release has a side effect: in the pause after a sentence, it starts turning up the volume, and the hiss in the pause rises with it, "breathing" between every phrase. The fix is to hang: after a peak, hold the volume where it is for a moment before releasing:
With a 200 ms hang, the script's pause comes out exactly as quiet as it went in; with none, 20 times louder. Spectrum Lab's AGC menu sets three pairs: fast (release 0.1 s, hang 50 ms) for CW, medium (0.4 s, 250 ms) for most voice, slow (1.5 s, 500 ms) for slow talkers and SSB. It also caps the gain at 60 dB, so an empty channel isn't amplified without limit.
Peaks that don't crackle
The volume knob goes up to +30 dB, and a speaker can only move so far: samples past ±1 get chopped flat, a hard clip, which sounds like crackling. Instead of a sharp corner at ±1, bend the curve smoothly, with tanh (the "hyperbolic tangent", a standard S-shaped curve), which is a straight line for small sounds and gently levels off for big ones:
The browser has a node for exactly this, the WaveShaperNode: you give it a curve, it bends every sample. Its curve only covers inputs from −1 to +1, so Spectrum Lab divides by 4 first and draws tanh(4x): together that's tanh of the original, with a slope of exactly 1 near zero, so normal sound passes untouched and only peaks are rounded.
- v: the volume as a factor, 10dB/20. From the script: 0.1 → 0.100, 1 → 0.762, 4 → 0.999. Never past 1, never a corner.
One stream that never stutters
Chapter 11's player scheduled every chunk as its own little sound, placed right after the previous one. It has three weak spots. Each chunk is resampled to the sound card's rate on its own, so what happens at the joins is up to the browser. The cushion is a fixed 150 ms, too little when the server's stream crosses the internet and stalls. And clock drift is fixed with a jolt: a dropped chunk or a pause to refill.
Spectrum Lab now plays everything through one continuous stream: a ring buffer (a fixed stretch of memory written round and round, like a circular track), a reader that walks through it at a fractional speed, and a little control loop. Watch it:
Chunks are written into the ring as they arrive (yellow). The sound card reads 128 samples at a time (blue), at its own rate. The distance between them is the cushion. The reader doesn't jump from sample to sample: its position is a fraction, advanced by the ratio of the two rates, and the sound between samples is read off a straight line (chapter 11's resampling, done continuously, so there are no joins at all). Then the control loop: if the cushion is bigger than the target, read a hair faster; if smaller, a hair slower, by at most 0.5%, a pitch change nobody can hear. If the ring ever runs dry, wait until the cushion is back and fade in over 5 ms.
In the chapter's script, the old player lost 5 chunks over 4 hours of a 50 ppm clock difference and, over the internet with a 300 ms stall every 20 seconds, had a gap and a skip per hour; the stream had none, holding a 350 ms cushion for the server's dongle (150 ms for your own). The code runs inside an AudioWorklet, a small program that the browser runs on its audio thread, so a busy page can't make the sound stutter.
- h: samples waiting in the ring; c: the cushion we want; i and f: the reader's position split into whole and fractional parts.
Recording what you hear
The last box in the chain hands the sound to the speakers and, at the same time, to a MediaStreamAudioDestinationNode: a tap that turns it into a stream the browser's MediaRecorder can compress. The recording is exactly what you heard, after squelch, noise reduction, AGC, volume and the limiter, saved as Opus in a .webm file (or .m4a in Safari) named after the frequency, mode and time. To keep the radio itself (to retune it later or study it in chapter 18's charts), you'd record the I/Q samples instead, 4.8 MB every second at 2.4 MS/s.
Lab: clean up a real voice
A live receiver with this chapter's controls, played through the continuous stream. Pick a voice channel, then switch each control on and off and listen. The chart shows the sound's spectrum before (gray) and after (blue) the cleanup.
In code
Show the real code (optional: everything it does is explained above)
The biquad (Biquad): the cookbook's numbers, then five multiplications per sample:
const w = (TAU * f) / fs, c = Math.cos(w), al = Math.sin(w) / (2 * Math.SQRT1_2), a0 = 1 + al;
const k = type === "lowpass" ? (1 - c) / 2 : (1 + c) / 2;
this.b0 = k / a0; this.b1 = (type === "lowpass" ? 2 * k : -2 * k) / a0; this.b2 = k / a0;
this.a1 = (-2 * c) / a0; this.a2 = (1 - al) / a0;
// per sample:
const y = this.b0 * x[i] + this.b1 * x1 + this.b2 * x2 - this.a1 * y1 - this.a2 * y2;
Noise reduction, one frame (NoiseReducer): window, FFT, a gain per bin, inverse FFT, window, overlap-add:
for (let i = 0; i < n; i++) re[i] = this.inp[i] * win[i]; // √Hann in
fft(re, im);
for (let b = 0; b <= n / 2; b++) {
const s = (this.smooth[b] = 0.8 * this.smooth[b] + 0.2 * (re[b] ** 2 + im[b] ** 2));
const nz = this.noise[b];
this.noise[b] = s < nz ? nz * (s / nz) ** 0.05 : nz * 1.01; // fall toward dips, rise slowly
let g = Math.max(floor, 1 - (NR_BIAS * over * this.noise[b]) / (s + 1e-20));
g = this.gain[b] = g > this.gain[b] ? 0.65 * this.gain[b] + 0.35 * g : 0.75 * this.gain[b] + 0.25 * g;
re[b] *= g; im[b] *= g; if (b && b < n / 2) { re[n - b] *= g; im[n - b] *= g; } // and the mirror bin
}
for (let i = 0; i < n; i++) im[i] = -im[i]; fft(re, im); // inverse FFT = conj, FFT, conj, ÷n
for (let i = 0; i < n; i++) this.ola[i] += (re[i] / n) * win[i]; // √Hann out, add
AGC with hang (Agc):
if (a >= this.env) { this.env = a; this.held = this.hang; } // a new peak: hold for `hang` samples
else if (this.held > 0) this.held--; // holding
else this.env = Math.max(lo, this.env * this.decay); // then release (lo caps the gain)
The stream (the AudioWorklet), for every sample the sound card asks for:
const step = (this.rate / sampleRate) * (1 + Math.max(-0.005, Math.min(0.005, (0.01 * (have - this.cushion)) / this.cushion)));
for (let i = 0; i < out.length; i++) {
if (this.w - this.r < 2) { this.on = false; this.fade = 0; break; } // ran dry: refill the cushion first
const k = Math.floor(this.r), f = this.r - k;
this.fade = Math.min(1, this.fade + 1 / 256); // ~5 ms fade-in after a gap
out[i] = this.fade * (this.ring[k & M] * (1 - f) + this.ring[(k + 1) & M] * f);
this.r += step;
}
Volume, limiter, recording (streamOut):
const vol = new GainNode(ctx), limiter = new WaveShaperNode(ctx, { oversample: "2x",
curve: Float32Array.from({ length: 1025 }, (_, i) => Math.tanh(4 * (i / 512 - 1))) });
const rec = ctx.createMediaStreamDestination();
player.connect(vol).connect(limiter).connect(ctx.destination);
limiter.connect(rec); // new MediaRecorder(rec.stream) records what you hear
Where this chapter's numbers come from. The numbers this chapter computes come from a short checking script behind this page, which also checks each claim and stops if one is wrong. Its output:
voice filter at 67 Hz (lowest CTCSS tone): -26.1 dB
voice filter at 150 Hz (a CTCSS tone): -12.3 dB
voice filter at 300 Hz (the low edge): -3.0 dB
voice filter at 1000 Hz (the middle of a voice): -0.1 dB
voice filter at 3000 Hz (the high edge): -3.0 dB
voice filter at 8000 Hz (hiss): -18.6 dB
√Hann² + √Hann² half a frame later: off from 1 by at most 7.3e-8
noise reduction 0.5: hiss in the pauses 8.5 dB lower, the tone changed by 0.1 dB
noise reduction 1: hiss in the pauses 11.5 dB lower, the tone changed by 0.2 dB
AGC, hang 0 ms: the pause comes out at 0.201 (it went in at 0.010)
AGC, hang 200 ms: the pause comes out at 0.010 (it went in at 0.010)
limiter: in 0.1 → out 0.100 (a hard clip would give 0.100)
limiter: in 0.5 → out 0.462 (a hard clip would give 0.500)
limiter: in 1.0 → out 0.762 (a hard clip would give 1.000)
limiter: in 2.0 → out 0.964 (a hard clip would give 1.000)
limiter: in 4.0 → out 0.999 (a hard clip would give 1.000)
4 hours, USB dongle, clocks 50 ppm apart:
one buffer per chunk: 0 gaps, 5 skips
one stream: 0 gaps, 0 skips (cushion stayed between 120 and 176 ms)
1 hour over the internet, a 300 ms stall every 20 s:
one buffer per chunk: 1 gaps, 1 skips
one stream: 0 gaps, 0 skips (cushion stayed between 26 and 380 ms)
all checks passed
Check yourself
Why does a biquad need only five multiplications when chapter 6's filters needed hundreds?
It reuses its own past outputs (the a-coefficients), so one click keeps ringing through the feedback instead of needing a weight for every past input. The price: the recipe must be chosen carefully, or the feedback can grow without end.
Why do the frames overlap by half, with a square-root Hann window used twice?
The window used twice is a Hann window, and Hann windows half a frame apart add up to exactly 1. So untouched frames rebuild the original sound perfectly, and changes fade smoothly between neighboring frames instead of clicking at the edges.
What makes over-eager noise reduction sound warbly and robotic, and what stops it?
Random bins of hiss poke above the estimate and their gains flicker on and off frame by frame: "musical noise". A gain floor (never more than −20 dB) and smoothing (rise fast, fall slowly) keep the gains calm.
The sound card runs at 48 000 samples a second and the radio's audio at 50 000. How far does the reader move per output sample, before the control loop's correction?
50 000 / 48 000 ≈ 1.042 input samples per output sample.
Last updated