---
title: "Capstone: clean the noise out of an audio clip"
heading: A melody buried under mains hum and hiss, deciding which filter removes which noise, notches for the hum and its harmonic, a windowed-sinc low-pass for the hiss, lining the output up after the filter's delay, and measuring the signal-to-noise ratio before and after
eyebrow: D5 · Lesson 13 · Capstone
xp: 80
---

::: hook
A recording made near a fluorescent light picks up a 60 Hz hum and its harmonics; a cheap microphone preamp adds a steady hiss across the whole band. Here's a one-second melody, four notes from 440 to 880 Hz, recorded with both, so badly that the noise carries more power than the music. Cleaning it up takes this course's tools in the right order: look at where each kind of noise lives in frequency, design a filter for each, apply them, and measure the improvement.
:::

::: play
- The response of two cascaded notch filters, at 60 Hz and 180 Hz, for a 16 kHz recording, with pole radius r.
- A notch close to the unit circle (r near 1) is narrow and leaves the music untouched, but rings for longer when the hum starts, letting hum through at the beginning.
- The readouts give each notch's −3 dB width and its transient's time constant.
:::

```sim plot
view: graph
x: f = 0..500
y: H = -40..3
slider: r = 0.98..0.9995 step 0.0005 = 0.995
plot: 20*log(abs((1 - 2*cos(2*pi*60/16000)*exp(-j*2*pi*f/16000) + exp(-2*j*2*pi*f/16000))/(1 - 2*r*cos(2*pi*60/16000)*exp(-j*2*pi*f/16000) + r^2*exp(-2*j*2*pi*f/16000))*(1 - 2*cos(2*pi*180/16000)*exp(-j*2*pi*f/16000) + exp(-2*j*2*pi*f/16000))/(1 - 2*r*cos(2*pi*180/16000)*exp(-j*2*pi*f/16000) + r^2*exp(-2*j*2*pi*f/16000))) + 1e-9) | samples: 1500 | label: two notches, dB (f in Hz)
marker: x = 440 | label: lowest note
readout: −3 dB width of each notch, Hz = (1 - r)*16000/pi | digits: 3
readout: transient time constant, ms = -1/ln(r)/16 | digits: 3
```

::: predict
## The melody's notes all lie between 440 and 880 Hz; the hiss is spread evenly from 0 to 8 kHz. If a low-pass at 1.5 kHz removed all the hiss above it, how much would the hiss's power fall?

- [ ] 1.5 dB
- [ ] 3 dB
- [x] About 7.3 dB
- [ ] About 15 dB

::: reveal
White noise has equal power per hertz, so keeping 1.5 kHz of an 8 kHz band keeps 1.5/8 of it: a reduction of 10 log₁₀(8/1.5) = 7.3 dB. The music, entirely below 1.5 kHz, passes untouched. The hum is a different problem: it's inside the passband, so it needs notches.
:::
:::

::: nameit
## A plan for the noise

1. **Hum** at 60 Hz and 180 Hz: two narrow notches (lesson 6), with zeros on the unit circle and poles at radius r. A narrow notch spares the music; its transient lasts about $-1/\ln r$ samples.
2. **Hiss** spread over the whole band: a low-pass just above the music. A windowed-sinc FIR filter (lesson 4) with 201 taps and a Hann window, cutting off at 1.5 kHz, attenuates 3 kHz by more than 100 dB and delays everything by exactly 100 samples.
3. **Alignment**: to compare the output with the clean signal, remove the FIR filter's delay by dropping its first (N − 1)/2 output samples.
4. **Measurement**: SNR = 10 log₁₀ of the clean signal's energy over the energy of the difference between the result and the clean signal.

## What each step buys

In the Python step's recording, the clean melody has 0.045 of power, the hum 0.145 and the hiss 0.0064. The SNR starts at −5.4 dB. The low-pass alone barely helps, −5.3 dB, because the hum is inside its passband; the notches alone reach 7.5 dB, limited by hiss; together they reach 12.4 dB.
:::

::: example
## What are the notches' width and transient at r = 0.995 for 16 kHz audio?

::: solution
1. **Notch width.**
   $$\begin{aligned} W &= \frac{(1 - 0.995) \times 16\,000}{\pi}\ \text{Hz} \\ &= 25.5\ \text{Hz} \end{aligned}$$
   so 440 Hz is untouched.
2. **Transient.**
   $$\begin{aligned} \tau &= -\frac{1}{\ln 0.995} \\ &= 199.5\ \text{samples} \\ &= 12.5\ \text{ms} \end{aligned}$$
   so the hum fades out over the first few tens of milliseconds.

**Answer:** each notch is 25.5 Hz wide, and its transient has a time constant of 12.5 ms.
:::
:::

::: example
## How much delay does the 201-tap low-pass add, and what's the SNR limit set by the hiss it leaves?

::: solution
1. **Delay.** The 201-tap filter delays everything by 100 samples:
   $$\frac{100}{16\,000\ \text{Hz}} = 6.25\ \text{ms}$$
2. **Hiss left.** The low-pass keeps 1.5 kHz of the hiss's 8 kHz band:
   $$0.0064 \times \frac{1.5}{8} = 0.0012$$
   of power, against the melody's 0.045.
3. **Best SNR.**
   $$10\log_{10}\frac{0.045}{0.0012} = 15.7\ \text{dB}$$
4. **Measured SNR.** The measured 12.4 dB also includes the notches' start-up transients and the hum that leaks through them.

**Answer:** a delay of 100 samples (6.25 ms), and the hiss it leaves limits the SNR to 15.7 dB at best.
:::
:::

::: example
## A recording has music at 0 dBFS, 60 Hz hum at −20 dBFS and hiss at −50 dBFS. A notch removes 40 dB of the hum. What SNR results?

::: solution
1. **Noise before.** Add the hum and hiss powers:
   $$\begin{aligned} N &= 10\log_{10}(10^{-2} + 10^{-5}) \\ &= -20.0\ \text{dBFS} \end{aligned}$$
   an SNR of 20 dB.
2. **Hum after the notch.** It drops 40 dB, to −60 dBFS.
3. **Noise after.** Together with the hiss:
   $$\begin{aligned} N &= 10\log_{10}(10^{-6} + 10^{-5}) \\ &= -49.6\ \text{dBFS} \end{aligned}$$
   an SNR of 49.6 dB, now set by the hiss.

**Answer:** the SNR rises from 20 dB to 49.6 dB, now set by the hiss.
:::
:::

::: check
kind: python

## Build the notch, the low-pass and the SNR meter, then clean the recording.

```python starter
import numpy as np

def notch(x, f0, fs, r=0.995):
    # Second-order notch: zeros on the unit circle at ±w0 = 2*pi*f0/fs and poles at radius r at the
    # same angles, so b = (1, -2cos w0, 1) and a = (1, -2r cos w0, r^2). Run it sample by sample over x.
    return np.array(x, dtype=float)

def lowpass_fir(numtaps, fc, fs):
    # Windowed-sinc low-pass: ideal sinc taps centered on (numtaps - 1)/2 with cutoff fc,
    # times a Hann window, scaled so the taps sum to 1.
    h = np.zeros(numtaps); h[numtaps//2] = 1.0
    return h

def snr_db(clean, test):
    # 10*log10 of the clean signal's energy over the energy of (test - clean).
    return 0.0

def denoise(x, fs):
    # Notch 60 Hz and 180 Hz, then low-pass with lowpass_fir(201, 1500, fs). Return an output the
    # same length as x and aligned with it: remove the FIR filter's delay of (201 - 1)/2 samples.
    return np.array(x, dtype=float)
```

```python solution
import numpy as np

def notch(x, f0, fs, r=0.995):
    w = 2*np.pi*f0/fs
    b = np.array([1.0, -2*np.cos(w), 1.0])
    a = np.array([1.0, -2*r*np.cos(w), r*r])
    y = np.zeros(len(x))
    x1 = x2 = y1 = y2 = 0.0
    for n, xn in enumerate(x):
        yn = b[0]*xn + b[1]*x1 + b[2]*x2 - a[1]*y1 - a[2]*y2
        x2, x1, y2, y1 = x1, xn, y1, yn
        y[n] = yn
    return y

def lowpass_fir(numtaps, fc, fs):
    n = np.arange(numtaps) - (numtaps - 1)/2
    h = 2*fc/fs*np.sinc(2*fc/fs*n)
    h = h*0.5*(1 - np.cos(2*np.pi*np.arange(numtaps)/(numtaps - 1)))
    return h/h.sum()

def snr_db(clean, test):
    return 10*np.log10(np.sum(clean**2)/np.sum((test - clean)**2))

def denoise(x, fs):
    y = notch(notch(x, 60, fs), 180, fs)
    h = lowpass_fir(201, 1500, fs)
    z = np.convolve(y, h)
    return z[100:100 + len(x)]
```

```python tests
_fs = 16000
_t = np.arange(_fs)/_fs
_notes = [440, 554.37, 659.26, 880]
_clean = sum(0.3*np.sin(2*np.pi*f*_t)*((_t >= 0.25*k) & (_t < 0.25*k + 0.25)) for k, f in enumerate(_notes))
_clean = _clean*np.minimum(1, np.minimum(_t, 1 - _t)/0.02)
_rng = np.random.default_rng(11)
_x = _clean + 0.5*np.sin(2*np.pi*60*_t) + 0.2*np.sin(2*np.pi*180*_t + 1) + 0.08*_rng.standard_normal(_fs)
_hum = notch(np.sin(2*np.pi*60*_t), 60, _fs)
assert np.sqrt(np.mean(_hum[8000:]**2)) < 0.01, "After its transient, the 60 Hz notch should remove a 60 Hz tone almost completely."
_tone = notch(np.sin(2*np.pi*440*_t), 60, _fs)
assert abs(np.sqrt(2*np.mean(_tone[8000:]**2)) - 1) < 0.01, "The notch should pass 440 Hz with its amplitude within 1%."
_h = lowpass_fir(201, 1500, _fs)
assert abs(_h.sum() - 1) < 1e-12 and np.allclose(_h, _h[::-1]), "The low-pass taps should be symmetric and sum to 1."
_H = abs(np.sum(_h*np.exp(-2j*np.pi*3000/_fs*np.arange(201))))
assert 20*np.log10(_H) < -40, f"The 201-tap low-pass should be at least 40 dB down at 3 kHz; it's {20*np.log10(_H):.1f} dB."
assert abs(snr_db(np.array([1.0, -1.0]), np.array([1.1, -0.9])) - 10*np.log10(100)) < 1e-9, "snr_db: signal energy 2 over error energy 0.02 is 20 dB."
_before, _after = snr_db(_clean, _x), snr_db(_clean, denoise(_x, _fs))
assert _before < 0 and _after > 12, f"Denoising should lift the SNR from {_before:.1f} dB to above 12 dB; got {_after:.1f} dB."
```

::: right
Right. Your notches remove the hum, your low-pass removes most of the hiss, and the SNR rises from −5.4 dB to 12.4 dB.
:::
:::

::: check
given: r = 0.99 | 0.995 | 0.999; s = 8 | 16 | 48
answer: (1 - r)*s*1000/pi
unit: Hz
tolerance: 0.5%

## A notch with poles at radius {r} runs at {s} kHz. About how wide is it at −3 dB?

::: right
Right. $(1 - r)f_s/\pi$ = {answer} Hz.
:::

::: misses
- [(1 - r)*s*1000] Divide by π.
- [any] Not yet. Width from the poles' distance to the circle.
:::
:::

::: check
given: s = 8 | 16 | 48; c = 1 | 1.5 | 3
answer: 10*log(s/2/c)
unit: dB
tolerance: 0.5%

## White noise fills 0 to half of {s} kHz. A low-pass at {c} kHz removes everything above it. By how much does the noise power fall?

::: right
Right. $10\log_{10}[(f_s/2)/f_c]$ = {answer} dB.
:::

::: misses
- [10*log(s/c)] The noise only reaches the Nyquist frequency, $f_s/2$.
- [20*log(s/2/c)] Powers use 10 log.
- [any] Not yet. The fraction of the band that's left.
:::
:::

::: check
given: N = 101 | 201 | 401; s = 16 | 44.1 | 48
answer: (N - 1)/2/s
unit: ms
tolerance: 0.5%

## A {N}-tap linear-phase filter runs at {s} kHz. How much must the output be advanced to line up with the input?

::: right
Right. $(N - 1)/2$ samples = {answer} ms.
:::

::: misses
- [any] Not yet. Half the filter's length.
:::
:::

::: check
given: P = 0.02 | 0.045 | 0.1; n = 0.001 | 0.005 | 0.05
answer: 10*log(P/n)
unit: dB
tolerance: 0.5%

## A signal of power {P} carries noise of power {n}. What's the SNR?

::: right
Right. $10\log_{10}(P_s/P_n)$ = {answer} dB.
:::

::: misses
- [20*log(P/n)] These are powers: 10 log.
- [any] Not yet. Power ratio in decibels.
:::
:::

::: check
kind: parts
given: H = -10 | -20 | -30; N = -40 | -50 | -60; a = 30 | 40

## Music at 0 dBFS carries hum at {H} dBFS and hiss at {N} dBFS. A notch removes {a} dB of the hum.

::: part
answer: -10*log(10^(H/10) + 10^(N/10))
unit: dB
tolerance: 0.5%

### What is the SNR before?

::: misses
- [any] Add the noise powers.
:::
:::

::: part
answer: -10*log(10^((H - a)/10) + 10^(N/10))
unit: dB
tolerance: 0.5%

### And after?

::: misses
- [any] The hum drops by {a} dB.
:::
:::
:::

::: check
kind: parts
given: r = 0.99 | 0.995 | 0.999; fs = 8 | 16

## A notch with pole radius {r} runs at {fs} kHz.

::: part
answer: (1 - r)*fs*1000/pi
unit: Hz
tolerance: 0.5%

### How wide is it?

::: misses
- [any] $(1 - r)f_s/\pi$.
:::
:::

::: part
answer: -1/ln(r)/(fs*1000)*1000
unit: ms
tolerance: 0.5%

### What is its transient's time constant?

::: misses
- [any] $-1/\ln r$ samples.
:::
:::
:::

::: explain
## Why does the low-pass filter alone barely improve this recording?

::: model
A filter can only remove noise at frequencies where the wanted signal isn't. The hiss is spread over the whole band, so a low-pass just above the melody removes most of it, but the hum sits at 60 and 180 Hz, inside the low-pass's passband, along with the melody. In this recording the hum carries about three times the melody's power and far more than the hiss, so removing hiss alone leaves the SNR almost unchanged. Narrow notches remove the hum at its exact frequencies without touching the notes, and only with both filters, each aimed at the noise in its own part of the spectrum, does the recording come clean.
:::
:::

::: practice

::: check
given: r = 0.9 | 0.9999; s = 1 | 96
answer: (1 - r)*s*1000/pi
unit: Hz
tolerance: 0.5%

## Notch width: r = {r}, {s} kHz?

::: misses
- [any] $(1 - r)f_s/\pi$.
:::
:::

::: check
given: s = 8 | 192; c = 0.2 | 2
answer: 10*log(s/2/c)
unit: dB
tolerance: 0.5%

## Noise reduction: low-pass at {c} kHz, {s} kHz sampling?

::: misses
- [any] $10\log[(f_s/2)/f_c]$.
:::
:::
:::
