Audio Augmentation
A keyword-spotting model trained on clean studio recordings of "yes" and "no" fails in a kitchen: the dishwasher hums, the speaker stands further away, talks faster, has a higher voice, and the word starts half a second later than in every training clip. Recording all those conditions is expensive; simulating them is cheap. Audio augmentation transforms training clips in ways that keep the label (the word, the bird species, the machine fault) and changes everything else. This lesson builds the five classic transforms on synthetic signals with NumPy and SciPy, so every effect can be measured; how audio is stored and loaded is covered in Images, Audio and Video as Arrays, and the full preparation pipeline in Preparing Audio Data.
The transforms
| Transform | What changes | Label preserved for... | Careful with... |
|---|---|---|---|
| time shift | where the event starts in the clip | keyword spotting, sound events | events cut off at the edge |
| background noise | adds noise or recorded ambience at a chosen signal-to-noise ratio | almost everything | very low SNR makes the event inaudible |
| time stretch | speed, keeping the pitch | speech content, most events | rhythm tasks (tempo is the label) |
| pitch shift | pitch, keeping the speed | speech content, events | speaker identity, music key, gender |
| SpecAugment | masks frequency bands and time spans of the spectrogram | speech recognition, classification | masking the only frames that contain the event |
As with images, augmentation is applied to training clips only, freshly at random each epoch; validation and test clips stay real.
A test signal
All examples use the same synthetic "word": two seconds at 16 kHz, silent except for a 0.5 s tone burst at 440 Hz with a harmonic at 880 Hz, starting at 0.6 s. A helper finds the dominant frequency and the start of the event, so each transform can be checked.
import numpy as np
sr = 16000
def make_clip(start=0.6, dur=0.5, f0=440.0):
t = np.arange(int(2 * sr)) / sr
burst = (t >= start) & (t < start + dur)
env = np.where(burst, np.sin(np.pi * (t - start) / dur) ** 2, 0.0) # smooth on and off
return env * (0.6 * np.sin(2 * np.pi * f0 * t) + 0.2 * np.sin(2 * np.pi * 2 * f0 * t))
def dominant_freq(x):
spec = np.abs(np.fft.rfft(x * np.hanning(len(x))))
return np.fft.rfftfreq(len(x), 1 / sr)[spec.argmax()]
def onset(x, thr=0.05):
return np.flatnonzero(np.abs(x) > thr)[0] / sr
def event_length(x, thr=0.05):
idx = np.flatnonzero(np.abs(x) > thr)
return (idx[-1] - idx[0]) / sr
clip = make_clip()
print(f"samples {len(clip)}, peak {np.abs(clip).max():.3f}")
print(f"dominant {dominant_freq(clip):.1f} Hz, onset {onset(clip):.3f} s, event {event_length(clip):.3f} s")samples 32000, peak 0.697
dominant 440.0 Hz, onset 0.644 s, event 0.413 s
The measured onset and length are a little inside 0.6 s and 0.5 s because the envelope fades in and out below the 0.05 threshold.
Shift and noise
A time shift moves the clip by a random number of samples. np.roll wraps the end round to the start, which is fine for continuous sounds; for a single event, padding with silence is more honest. Noise mixing scales the noise so that the signal-to-noise ratio hits a target in decibels: SNR = 10 log10(signal power / noise power), so the noise must be multiplied by sqrt(P_signal / (P_noise * 10 ** (snr_db / 10))).
import numpy as np
sr = 16000
rng = np.random.default_rng(0)
t = np.arange(2 * sr) / sr
env = np.where((t >= 0.6) & (t < 1.1), np.sin(np.pi * (t - 0.6) / 0.5) ** 2, 0.0)
clip = env * (0.6 * np.sin(2 * np.pi * 440 * t) + 0.2 * np.sin(2 * np.pi * 880 * t))
onset = lambda x: np.flatnonzero(np.abs(x) > 0.05)[0] / sr
def shift(x, max_s=0.4):
n = int(rng.integers(-int(max_s * sr), int(max_s * sr) + 1))
out = np.zeros_like(x)
if n >= 0:
out[n:] = x[:len(x) - n]
else:
out[:n] = x[-n:]
return out, n / sr
def add_noise(x, snr_db):
noise = rng.normal(0, 1, len(x))
active = np.abs(x) > 0 # measure the signal where the event is
p_sig = np.mean(x[active] ** 2)
scale = np.sqrt(p_sig / (np.mean(noise ** 2) * 10 ** (snr_db / 10)))
return x + scale * noise, scale * noise
shifted, secs = shift(clip)
print(f"shift by {secs:+.3f} s: onset {onset(clip):.3f} -> {onset(shifted):.3f} s")
for snr in [20, 10, 0]:
noisy, noise = add_noise(clip, snr)
active = np.abs(clip) > 0
measured = 10 * np.log10(np.mean(clip[active] ** 2) / np.mean(noise[active] ** 2))
print(f"target SNR {snr:2d} dB -> measured {measured:5.2f} dB, noise std {noise.std():.4f}")shift by +0.281 s: onset 0.644 -> 0.924 s
target SNR 20 dB -> measured 20.03 dB, noise std 0.0274
target SNR 10 dB -> measured 10.02 dB, noise std 0.0866
target SNR 0 dB -> measured 0.05 dB, noise std 0.2739
The measured ratios land within a fraction of a decibel of the targets (the noise is random). In practice the noise comes from real recordings of the target environment (cafés, cars, wind), mixed at an SNR drawn per clip from a range such as 5 to 20 dB.
Stretch and pitch shift
Changing the playback speed by resampling changes both duration and pitch, like a tape played too fast. To change only one, a time stretch works on the short-time spectrum: it cuts the signal into overlapping windowed frames (an STFT), reads those frames at a different speed and adds them back together. Simply re-spacing the frames makes neighbouring frames overlap out of phase, so a phase vocoder also adjusts each frequency bin's phase so that it keeps advancing at that bin's true frequency. A pitch shift is then a stretch followed by resampling back to the original length. librosa.effects.time_stretch and pitch_shift work this way; here is a compact version in NumPy:
import numpy as np
from scipy.signal import resample
sr = 16000
t = np.arange(2 * sr) / sr
env = np.where((t >= 0.6) & (t < 1.1), np.sin(np.pi * (t - 0.6) / 0.5) ** 2, 0.0)
clip = env * (0.6 * np.sin(2 * np.pi * 440 * t) + 0.2 * np.sin(2 * np.pi * 880 * t))
def dominant(x):
spec = np.abs(np.fft.rfft(x * np.hanning(len(x))))
return np.fft.rfftfreq(len(x), 1 / sr)[spec.argmax()]
def length(x):
idx = np.flatnonzero(np.abs(x) > 0.05)
return (idx[-1] - idx[0]) / sr
def stft(x, n_fft=1024, hop=256):
win = np.hanning(n_fft)
n = (len(x) - n_fft) // hop + 1
return np.array([np.fft.rfft(x[i * hop:i * hop + n_fft] * win) for i in range(n)])
def istft(S, n_fft=1024, hop=256):
win = np.hanning(n_fft)
out = np.zeros(len(S) * hop + n_fft)
norm = np.zeros_like(out)
for i, spec in enumerate(S):
out[i * hop:i * hop + n_fft] += np.fft.irfft(spec, n_fft) * win
norm[i * hop:i * hop + n_fft] += win ** 2
return out / np.maximum(norm, 1e-8)
def stretch(x, rate, n_fft=1024, hop=256):
"""Phase-vocoder time stretch: rate > 1 is faster (shorter), pitch unchanged."""
S = stft(x, n_fft, hop)
expected = 2 * np.pi * hop * np.arange(S.shape[1]) / n_fft # phase advance per hop
phase = np.angle(S[0])
frames = []
for pos in np.arange(0, len(S) - 1, rate): # read frames at the new speed
i, frac = int(pos), pos - int(pos)
mag = (1 - frac) * np.abs(S[i]) + frac * np.abs(S[i + 1])
frames.append(mag * np.exp(1j * phase))
dphi = np.angle(S[i + 1]) - np.angle(S[i]) - expected
dphi -= 2 * np.pi * np.round(dphi / (2 * np.pi)) # wrap to [-pi, pi]
phase = phase + expected + dphi # keep each bin's true frequency
return istft(np.array(frames), n_fft, hop)
def pitch_shift(x, semitones):
factor = 2 ** (semitones / 12)
y = stretch(x, 1 / factor) # longer by the factor, same pitch
return resample(y, len(x)) # squeeze back: pitch rises by the factor
versions = {"original": clip,
"resample x1.25 (tape)": resample(clip, int(len(clip) / 1.25)),
"stretch rate 1.25": stretch(clip, 1.25),
"stretch rate 0.8": stretch(clip, 0.8),
"pitch +3 semitones": pitch_shift(clip, 3)}
for name, v in versions.items():
print(f"{name:22s} dominant {dominant(v):6.1f} Hz event {length(v):.3f} s")original dominant 440.0 Hz event 0.413 s
resample x1.25 (tape) dominant 550.0 Hz event 0.330 s
stretch rate 1.25 dominant 440.0 Hz event 0.326 s
stretch rate 0.8 dominant 439.9 Hz event 0.512 s
pitch +3 semitones dominant 521.0 Hz event 0.411 s
The "tape" version is shorter and higher (550 Hz instead of 440). The phase-vocoder stretch keeps 440 Hz while the event shrinks to 0.326 s (rate 1.25, expected 0.413 / 1.25 = 0.330) or grows to 0.512 s (rate 0.8, expected 0.516), and the pitch shift raises the tone to 521 Hz without changing the length; the exact value for +3 semitones is 440 times 2 to the power 3/12, 523.3 Hz, and the small error comes from interpolating between frames. Typical training ranges are rates of 0.8 to 1.25 and shifts of a few semitones.
SpecAugment
Many audio models work on spectrograms rather than waveforms. SpecAugment augments the spectrogram directly with masks: a few random bands of frequency bins and a few random spans of time frames are set to zero (or the mean). It is cheap, works on the features the model actually sees, and became a standard part of speech-recognition training. (The original method also warps time; that part is often left out.)
import numpy as np
from scipy.signal import stft
sr = 16000
rng = np.random.default_rng(2)
t = np.arange(2 * sr) / sr
env = np.where((t >= 0.6) & (t < 1.1), np.sin(np.pi * (t - 0.6) / 0.5) ** 2, 0.0)
clip = env * (0.6 * np.sin(2 * np.pi * 440 * t) + 0.2 * np.sin(2 * np.pi * 880 * t)) + 0.001 * rng.normal(0, 1, len(t))
f, frames, Z = stft(clip, fs=sr, nperseg=512, noverlap=384)
logspec = np.log(np.abs(Z) ** 2 + 1e-10)
print("log spectrogram:", logspec.shape, "(frequency bins x time frames)")
def spec_augment(S, n_freq_masks=2, max_f=20, n_time_masks=2, max_t=25):
n_f, n_t = S.shape
mask = np.zeros(S.shape, dtype=bool)
for _ in range(n_freq_masks):
w = int(rng.integers(0, max_f + 1)); f0 = int(rng.integers(0, n_f - w + 1))
mask[f0:f0 + w, :] = True
for _ in range(n_time_masks):
w = int(rng.integers(0, max_t + 1)); t0 = int(rng.integers(0, n_t - w + 1))
mask[:, t0:t0 + w] = True
return np.where(mask, S.mean(), S), mask
aug, masked = spec_augment(logspec)
print(f"masked cells: {masked.mean():.1%}")
row_440 = int(np.argmin(np.abs(f - 440)))
event = (frames >= 0.6) & (frames < 1.1)
kept = ~masked[row_440, event]
print(f"440 Hz row during the event: {int(kept.sum())} of {int(event.sum())} frames still visible")log spectrogram: (257, 251) (frequency bins x time frames)
masked cells: 11.8%
440 Hz row during the event: 51 of 63 frames still visible
About 12 % of the spectrogram is masked and a time mask hides part of the event, yet most of it is still visible (51 of 63 frames of the 440 Hz row), so the label "this word was spoken" still holds. Mask sizes are hyperparameters: masks so wide that they routinely hide the entire event teach the model to guess.
Pitfalls
- Label-changing transforms: pitch shifting breaks speaker identification and music-key tasks; time stretching breaks tempo or speaking-rate tasks; shifting can push a short event out of the clip.
- Augmenting the evaluation set: validation and test clips must be real recordings from the target conditions, or you measure performance on your own simulation.
- Recording-level leakage: several clips cut from the same recording session belong to the same split; augmentation does not fix a split that lets the same speaker appear on both sides (split strategies).
- Clipping: adding noise or gain can push samples beyond the valid range [-1, 1]. Rescale or clip consistently.
Practice
- A clip has signal power 0.02. What noise power gives an SNR of 10 dB?
Answer
10 dB means a power ratio of 10, so the noise power is 0.02 / 10 = 0.002 (noise standard deviation about 0.045 for zero-mean noise).
- A bird-species classifier is trained on 5-second clips. Which augmentations are safe?
Answer
Time shifts, background noise (wind, rain, other habitats), small gain changes and SpecAugment with moderate masks. Pitch shifting is risky, since many species are told apart by the frequency of their song; time stretching also changes the song's rhythm, which can be a species cue. Use small ranges if at all.
Test yourself
Resampling a clip to play 25 % faster changes...
- only the duration
- only the pitch
- both duration and pitch
- neither
What does SpecAugment do?
- Adds reverb to the waveform
- Masks random frequency bands and time spans of the spectrogram
- Changes the sample rate
- Removes silence
For which task is pitch shifting an invalid augmentation?
- Recognising the word 'yes'
- Detecting a dog bark
- Identifying which speaker is talking
- Detecting glass breaking
Noise is mixed at a target SNR of 0 dB. What does that mean?
- No noise
- The noise has the same power as the signal
- The noise is 10 times stronger
- The signal is removed