Speech enhancement: subtracting noise without losing the signal
语音增强
Derive three spectral gains, reconstruct waveforms, and test calibration, phase and measurement assumptions.
speech-enhancementA quieter recording can lose the word you wanted
Imagine a voice message recorded beside a fan. Turning down the volume reduces the fan and the voice together. Speech enhancement tries to retain a chosen speech signal while reducing unwanted sound. The target must be stated: the clean source, the speech as recorded in a room, or an intelligible message can demand different processing.
A useful starting point is a few moments containing only the fan. Estimate its spectrum, then attenuate frequencies whose observed energy looks like that noise. Boll’s 1979 method estimates average noise magnitude, subtracts it from each observed magnitude and retains the mixture phase. Negative results are rectified to zero. Local noise stationarity and a usable nonspeech interval are assumptions, not information automatically supplied by the recording. Original method
There are two immediate failure cases. A soft consonant can occupy a bin that the noise estimate would remove. A fan that changes speed can make yesterday’s estimate inappropriate. Suppression can also leave isolated fluctuating spectral components, heard as tonal artifacts often called musical noise. Averaging, a gain floor and slower attenuation trade residual noise against speech distortion; each needs evaluation.
The STFT article explains the time-frequency representation used below. We will compare three gains, reconstruct actual waveforms and deliberately reuse an incorrect noise profile. The examples are constructed tones, so their numerical improvement says nothing about human speech quality.
Choose the quantity before subtracting it
Let be target speech, additive interference, and their observed sum. Capital letters denote complex coefficients in the same STFT bin; denotes conjugation.
Complex spectra add exactly. Magnitudes generally do not; powers include a cross term. Uncorrelated zero-mean components remove that cross term in expectation, not necessarily in an individual frame. Keeping the mixture phase is an approximation even if a magnitude estimate is excellent. Boll’s construction explicitly replaces the unavailable noise spectrum using a measured magnitude bias and observed phase. Estimator and error
For complete noise-only calibration frames, calculate both estimates independently:
The mean squared magnitude differs from the square of the mean magnitude. A calibration interval containing speech learns some of the desired signal as “noise.” Padding frames with zeros can also bias these estimates, so the implementation excludes padded calibration frames.
Write , with estimated noise magnitude and power . With subtraction factor , the following raw gains multiply the complex mixture coefficient, hence are amplitude gains:
Power subtraction needs the square root. The third expression is a plug-in Wiener-shaped gain: at , estimate speech power as the positive part of and insert it into a speech-to-total-power ratio. It is not an oracle estimate of the true powers. For , and , the three gains are , and . The factor, floor and smoothing in this teaching implementation are explicit extensions, not a claim that every variant is Boll’s original algorithm.
Why does Wiener filtering use a power ratio as an amplitude gain? Restrict the estimate to with a real scalar . For zero-mean, uncorrelated speech and noise with second moments , expand the expected squared error:
The positive second derivative makes this the unique minimum when total power is positive. Gaussianity is unnecessary for this linear-class result; optimality among all nonlinear estimators is a different claim. The ratio is also given in Le Roux and colleagues’ Wiener example. Power-ratio reference
A four-case independent construction with speech values and noise values gives , , optimal gain and risk . With correlated noise , gain instead recovers exactly: the omitted cross term matters.
Neural enhancement can estimate gains while retaining DSP analysis and synthesis. The 2018 RNNoise design predicts gains for 22 bands from 42 features, with recurrent processing and a pitch filter. Its bands distribute each bin’s weight across neighbors, and the described target is a square root of clean-to-noisy band energy. Hybrid architecture
Here is a nonnegative band weight and the weights sum to one across bands. This target must be distinguished from . In a coherent cancellation example, , and , the raw square-root ratio is . Thus a finite measured ratio is not universally bounded by one. A bounded predictor or explicit clipping changes the target. At zero noisy energy it is undefined; an implementation needs a validity mask, not a pretend label. RNNoise’s paper explicitly ignores undefined-band training losses. Gain definition and training
For reconstruction, let be an even window length, , a sine window, and a windowed spectrum. The implementation uses an ordinary unnormalized FFT and its matching inverse:
Window terms outside its support from 0 to are zero. The inverse transform gives a windowed frame; multiplying by the synthesis window produces the squared-window denominator. Our sine-window squares add to one over adjacent half-overlapped frames. Padding covers the output boundary, and explicit division handles every retained sample. This window differs from RNNoise’s published window. Centered windows and whole-recording processing make the example offline.
Finally, impose floor and optional decay factor :
The stored gain can fall only as fast as the recurrence allows, so noise may persist after a change. This simple rule omits RNNoise’s pitch processing and energy compensation. The fixed modern implementation also operates on delayed spectra; its behavior should not be inferred solely from the 2018 diagram. Current fixed source
A calibration recording and three reconstructed outputs
Run this complete program with Python 3.12 and NumPy 1.26.4. It uses at most 4,096 real samples bounded by 8 in magnitude, even windows from 8 to 256 samples, and half-window hops. Calibration requires at least one complete unpadded frame. Subtraction factor is bounded by 4, floor by 1, and decay by 0.99. Extremely small gain denominators at or below are treated as zero before applying the floor; this is a numerical policy.
band_target consumes supplied spectra to inspect the energy ratio; it does not run a neural network. Undefined entries have a false validity flag and a stored zero that must not be treated as a valid target. mse_score reports an explicit state for silent references or exact recovery instead of inventing finite decibel values.
"""Original bounded offline spectral enhancement; no learned acoustic model.
NumPy only. Sine-window STFT, 50% overlap, explicit squared-window division.
A separate, declared noise-only calibration recording is required.
"""
import json
import numpy as np
def signal(values):
raw=np.asarray(values)
if raw.dtype.kind not in 'fiu' or raw.ndim!=1 or not 1<=len(raw)<=4096:raise ValueError('Use 1..4096 real samples')
x=raw.astype(float)
if not np.isfinite(x).all() or np.max(abs(x))>8:raise ValueError('Finite samples bounded by 8 required')
return x
def analyze(values,frame=64):
x=signal(values)
if type(frame) is not int or not 8<=frame<=256 or frame%2:raise ValueError('Use an even frame from 8..256')
hop=frame//2;left=hop;work=np.pad(x,(left,frame));work=np.pad(work,(0,(-(len(work)-frame))%hop))
starts=np.arange(0,len(work)-frame+1,hop);w=np.sin(np.pi*(np.arange(frame)+.5)/frame)
z=np.fft.rfft(np.array([work[i:i+frame]*w for i in starts]),axis=1)
return dict(z=z,window=w,starts=starts,left=left,length=len(x),work_length=len(work),hop=hop)
def synthesize(state,z):
z=np.asarray(z);w=state['window']
if z.shape!=state['z'].shape or not np.isfinite(z).all():raise ValueError('Matching finite spectra required')
frames=np.fft.irfft(z,n=len(w),axis=1);out=np.zeros(state['work_length']);den=out.copy()
for start,part in zip(state['starts'],frames):out[start:start+len(w)]+=part*w;den[start:start+len(w)]+=w*w
region=slice(state['left'],state['left']+state['length'])
if np.any(den[region]<1e-12):raise ValueError('Uncovered output samples')
return out[region]/den[region]
def noise_profile(calibration,frame=64):
a=analyze(calibration,frame);start=a['starts']-a['left'];valid=(start>=0)&(start+frame<=a['length'])
if not valid.any():raise ValueError('Calibration needs one complete unpadded frame')
magnitude=abs(a['z'][valid])
return dict(magnitude=magnitude.mean(axis=0),power=(magnitude**2).mean(axis=0),frames=int(valid.sum()))
def gains(magnitude,profile,mode='magnitude',factor=1.,floor=0.,decay=0.):
a=np.asarray(magnitude)
if a.dtype.kind not in 'fiu' or a.ndim!=2 or not 1<=a.shape[0]<=1026 or not 5<=a.shape[1]<=129 or not np.isfinite(a).all() or np.any((a<0)|(a>2048)):raise ValueError('Invalid magnitude array')
if mode not in ('magnitude','power','wiener'):raise ValueError('Unknown gain mode')
for v,lo,hi in [(factor,0,4),(floor,0,1),(decay,0,.99)]:
if type(v) not in (int,float) or not np.isfinite(v) or not lo<=v<=hi:raise ValueError('Invalid gain parameter')
key='magnitude' if mode=='magnitude' else 'power';p=np.asarray(profile[key])
if p.dtype.kind not in 'fiu' or p.shape!=(a.shape[1],) or not np.isfinite(p).all() or np.any((p<0)|(p>4194304)):raise ValueError('Invalid noise profile')
a=a.astype(float);p=p.astype(float)
base=a if mode=='magnitude' else a*a
ratio=np.divide(factor*p,base,out=np.zeros_like(base,dtype=float),where=base>1e-20)
raw=np.maximum(1-ratio,0.);raw[base<=1e-20]=0.
if mode=='power':raw=np.sqrt(raw)
raw=np.maximum(raw,floor);out=raw.copy();previous=np.zeros(a.shape[1])
for t in range(len(out)):out[t]=np.maximum(raw[t],decay*previous);previous=out[t]
return out
def enhance(values,calibration,mode='magnitude',frame=64,factor=1.,floor=0.,decay=0.):
a=analyze(values,frame);p=noise_profile(calibration,frame);g=gains(abs(a['z']),p,mode,factor,floor,decay)
y=synthesize(a,a['z']*g)
return dict(values=y,gains=g,profile=p,frame_starts=a['starts']-a['left'],hop=a['hop'])
def mse_score(reference,estimate):
s=signal(reference);y=signal(estimate)
if s.shape!=y.shape:raise ValueError('Matching signals required')
energy=float(s@s);error=float(np.sum((s-y)**2));mse=error/len(s)
return dict(mse=mse,snr_db=None if energy==0 or error==0 else float(10*np.log10(energy/error)),
status='silent-reference' if energy==0 else ('exact' if error==0 else 'finite'))
def wiener_risk(g,speech_power=1.,noise_power=1.):
for v in (g,speech_power,noise_power):
if type(v) not in (int,float) or not np.isfinite(v):raise ValueError('Finite real scalars required')
if not -4<=g<=4 or not 0<=speech_power<=64 or not 0<=noise_power<=64 or speech_power+noise_power==0:raise ValueError('Invalid powers or gain')
return (g-1)**2*speech_power+g*g*noise_power
def band_target(speech,noisy,weights):
s=np.asarray(speech,dtype=complex);y=np.asarray(noisy,dtype=complex);w=np.asarray(weights)
if s.ndim!=1 or s.shape!=y.shape or not 1<=len(s)<=129 or w.ndim!=2 or w.shape[1]!=len(s) or not 1<=len(w)<=32 or w.dtype.kind not in 'fiu':raise ValueError('Invalid band arrays')
if not all(np.isfinite(x).all() for x in [s,y,w]) or max(np.max(abs(s)),np.max(abs(y)))>2048 or np.any((w<0)|(w>1)) or not np.allclose(w.sum(axis=0),1,atol=1e-12,rtol=0):raise ValueError('Use finite spectra and a partition of unity')
es=w@(abs(s)**2);ey=w@(abs(y)**2);defined=ey>1e-20;raw=np.sqrt(np.divide(es,ey,out=np.zeros_like(es),where=defined))
return dict(raw=raw,clipped=np.minimum(raw,1),defined=defined)
def demo():
n=np.arange(512);speech=.6*np.sin(2*np.pi*5*n/64);noise=.4*np.sin(2*np.pi*17*n/64+.3);mixture=speech+noise
calibration=.4*np.sin(2*np.pi*17*np.arange(256)/64+.3)
methods={}
for mode in ['magnitude','power','wiener']:
r=enhance(mixture,calibration,mode,floor=.02)
methods[mode]=dict(score=mse_score(speech,r['values']),values=r['values'][64:96].tolist(),gain_frame=r['gains'][4].tolist())
changed=.4*np.sin(2*np.pi*5*n/64+.3);stale=enhance(speech+changed,calibration,'wiener',floor=.02)
p={'magnitude':np.full(5,2.),'power':np.full(5,4.)};a=np.full((1,5),3.)
band=band_target([1],[-.5],[[1.]])
return dict(rate=8000,frame=64,hop=32,calibration_frames=noise_profile(calibration)['frames'],
before=mse_score(speech,mixture),methods=methods,stale_calibration=mse_score(speech,stale['values']),
three_gains={mode:float(gains(a,p,mode)[0,0]) for mode in methods},
risk=[dict(gain=g,risk=wiener_risk(g)) for g in [0.,.25,.5,.75,1.]],
cancellation=dict(raw_band_gain=float(band['raw'][0]),clipped=float(band['clipped'][0]),
clean_real=1.,mixture_real=-.5,clipped_estimate=-.5),
waveform=dict(speech=speech[64:96].tolist(),mixture=mixture[64:96].tolist()))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
At the illustrative 8 kHz rate, 512 samples contain a target sinusoid of amplitude 0.6 and a different-frequency interfering sinusoid of amplitude 0.4. The separate 256-sample noise recording supplies seven complete 64-sample calibration frames. Before processing, MSE is 0.08 and SNR is about 3.521825 dB. With gain floor 0.02, magnitude subtraction, power subtraction and plug-in Wiener give MSE about 0.000244987, 0.000729192 and 0.000382185 respectively.
Changing the interference frequency to the target’s frequency while keeping the old calibration leaves MSE about 0.079975792. The successful case exploits spectral separation in constructed signals; the failed case tests what the estimator actually knows.
For samples, frames and window length , analysis and reconstruction cost ; gain processing costs . The offline program stores values. Calibration has the same transform cost for its own frames. A -band, -bin energy target costs ; scalar Wiener risk costs .
The error measure must match the intended use
The program reports fixed-reference waveform error:
Lower MSE can reward a gain change without improving intelligibility. SI-SDR removes a scalar gain difference, but that also makes it unsuitable for detecting every loudness error. Le Roux and colleagues explain how reference deformation and scale conventions change the question an SDR metric answers. Metric assumptions
A real experiment should preserve clean/noisy pairing, level and alignment, specify whether room reverberation belongs to the target, and hold out speakers and noise conditions. Compare the unprocessed waveform and simple spectral baselines before adding a model. Evaluate intelligibility, perceptual artifacts, downstream recognition where relevant, and processing delay separately. This program has no real speech corpus, listening study, network training or real-time guarantee.
Enhancement can erase information. A nonnegative real gain cannot generally repair an incorrect phase, recover a source where the mixture cancels to zero, or infer which of two voices the listener wants without additional assumptions. Keep the original recording when comparing outputs, and inspect errors where attenuation appears most successful.
Four checks before trusting a denoiser
-
Quantity check. An observed magnitude is 3 and estimated noise power is 4. What amplitude gain implements power subtraction? How does it differ from the plug-in Wiener gain?
Answer: Retained power is , so the gain is . The plug-in Wiener gain is . Applying the latter as if it were the former attenuates amplitude more strongly.
-
Risk by hand. Independent zero-mean speech and noise have powers 1 and 4. Find the best scalar gain and its mean squared error. Is the result a theorem about every nonlinear denoiser?
Answer: The derivative vanishes at . The error is . The optimization searched scalar linear gains; it did not search all nonlinear functions.
-
Cancellation boundary. A bin has , . Compute the noisy coefficient, raw band gain and output after clipping that gain to 1. Can clipping restore the target?
Answer: and . The clipped output is , whereas the target is positive. This example needs a sign/phase correction; a gain constrained to the interval from 0 to 1 cannot provide it.
-
Transfer check. A denoiser succeeds with stationary fan noise but fails when the fan changes speed. Which experiment distinguishes a stale profile from a reconstruction bug?
Answer: First verify identity reconstruction with unchanged spectra. Then hold the waveform fixed and compare the old profile with a separate, genuinely noise-only calibration from the changed condition. Improvement from the new profile implicates estimation mismatch. If both fail, inspect phase overlap and target/noise ambiguity; do not silently use clean speech from the evaluation target as calibration.
From estimated noise to learned suppression
Boll supplies a concrete classical estimator; RNNoise shows how learned gain prediction can cooperate with signal processing. The useful progression is to identify the estimated quantity, its supervision and its failure conditions before increasing model size. The paper’s band target, a Wiener power ratio and the program’s three gains are related constructions with different meanings. Classical estimator Learned gains
The fixed RNNoise code is useful for seeing delayed processing and state. Our original NumPy program intentionally stops at transparent components, so running it is not a reproduction of that library. Recovering multiple source waveforms poses a separate source-separation problem. For the representation used here, revisit STFT.
Make a prediction, then check
Magnitude is3 and estimated noise power is4. Which gain implements power subtraction before waveform synthesis?
Learning objectives
- Distinguish magnitude subtraction, power subtraction and Wiener gain.
- Derive the optimal scalar gain under explicit second-moment assumptions.
- Reconstruct a waveform and explain noise calibration, phase and smoothing failures.
- Separate synthetic error measurements from real speech quality.
Prerequisites & connections
Explore related knowledge →References
- Suppression of Acoustic Noise in Speech Using Spectral Subtraction
Steven F. Boll · 1979 - A Hybrid DSP/Deep Learning Approach to Real-Time Full-Band Speech Enhancement
Jean-Marc Valin · 2018 - SDR – half-baked or well done? (arXiv v1)
Jonathan Le Roux; Scott Wisdom; Hakan Erdogan; John R. Hershey · 2018 - RNNoise denoise.c at70f1d25
Xiph.Org RNNoise contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked scoped Boll magnitude subtraction and mixture phase, independent second-moment Wiener risk, separate magnitude/power estimates, RNNoise band targets and cancellation, waveform overlap-add, state/floor policies and metric assumptions. Eight paired equations and four explained exercises. Original offline NumPy waveform components with separate noise calibration, not neural speech inference or corpus quality results.
- Verified sine-window reconstruction including short/odd inputs, unpadded calibration7, gains1/3/sqrt5/3/5/9, independent risk optimum0.2 with risk0.8, correlated-noise counterexample, explicit band gain2 clipping and wrong sign. Synthetic MSE0.08 versus three values below0.001; stale calibration0.079975792.
- Four computed SVGs bind exact bilingual MDX. The two-topic group passed nine numeric/encoding checks and 12 isolated language/width cases with four fallback fonts; four representative actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- Suppression of Acoustic Noise in Speech Using Spectral Subtraction · Read journal pages113–114 background and II.A–F, plus page115 rectification limitation. Physical page2 inspected. Magnitude subtraction and mixture-phase approximation; no helicopter benchmark or full residual suppressor reproduced.
- A Hybrid DSP/Deep Learning Approach to Real-Time Full-Band Speech Enhancement · Read abstract, sectionII signal model and page2 band/pitch/features, plus sectionIII architecture, gain loss, undefined-band masking and smoothing opening. Physical page2 inspected; no full training or performance replication. The2018 design is separate from the fixed modern source.
- SDR – half-baked or well done? (arXiv v1) · Read sections2.1–2.3 on reference deformation, SNR and scalar-projection SI-SDR, and the Wiener formula in section3.3; physical page2 inspected. No experimental tables reproduced.
- RNNoise denoise.c at70f1d25 · Read445–512: band normalization, delayed spectra, pitch/network calls and0.6 gain hold with energy compensation. Full README and BSD3-clause COPYING read. No upstream code/model executed or copied.
Related topics