TExcelTAD

Preparing Audio Data

An audio clip is a long array of air-pressure samples (Images, Audio and Video as Arrays). Clips in a real dataset disagree on almost everything: one is a 44.1 kHz stereo music file, the next a 16 kHz mono phone call, a third starts with two seconds of silence, a fourth has traffic noise underneath. Models want one sample rate, one channel layout, one length and, usually, a time-frequency picture instead of raw samples. This lesson prepares a synthetic recording step by step with NumPy and SciPy, keeping its transcript timestamps in sync.

The steps

Step Why Typical choice
resample a model has one fixed sample rate; 1 s means a different number of samples at each rate 16 kHz for speech, 22.05 or 44.1 kHz for music
channels stereo vs mono changes the array shape average to mono unless direction matters
trim / pad batches need equal lengths; leading silence wastes input trim silence by energy, then pad or crop to a fixed duration
noise background noise varies by device and place measure it (signal-to-noise ratio), filter or keep as is, or add it as augmentation
features most models learn better from time-frequency pictures waveform, spectrogram, log-Mel spectrogram
alignment transcripts and event labels have timestamps shift and scale them with every trim and resample
normalise features on a common scale per-feature mean/std from the training clips

Sample rate, channels, trimming and alignment

The example builds a 44.1 kHz stereo recording: half a second of quiet room noise, a one-second "word" (a tone with a harmonic, louder on the left), then more quiet. A transcript says the word starts at 0.50 s and ends at 1.50 s.

python · try it yourself
import numpy as np
from scipy.signal import resample_poly

rng = np.random.default_rng(0)
sr = 44_100
t = np.arange(int(2.2 * sr)) / sr
word = (t >= 0.5) & (t < 1.5)
tone = np.where(word, 0.6 * np.sin(2 * np.pi * 440 * t) + 0.2 * np.sin(2 * np.pi * 880 * t), 0.0)
left = tone + 0.01 * rng.standard_normal(t.size)
right = 0.5 * tone + 0.01 * rng.standard_normal(t.size)
stereo = np.stack([left, right], axis=1)                 # shape (samples, 2)
transcript = [("hello", 0.50, 1.50)]
print("input:", stereo.shape, "at", sr, "Hz =", round(stereo.shape[0] / sr, 2), "s")

mono = stereo.mean(axis=1)                               # 1. channels
target = 16_000
audio = resample_poly(mono, up=160, down=441)            # 2. 44100 * 160 / 441 = 16000
print("mono, resampled:", audio.shape, "at", target, "Hz =", round(audio.size / target, 2), "s")

frame = 400                                              # 3. trim silence: 25 ms frames
rms = np.sqrt(np.mean(audio[: audio.size // frame * frame].reshape(-1, frame) ** 2, axis=1))
loud = np.flatnonzero(rms > 0.1 * rms.max())
start, end = loud[0] * frame, (loud[-1] + 1) * frame
trimmed = audio[start:end]
print("trimmed to samples", int(start), "-", int(end), "=", round(trimmed.size / target, 3), "s")

fixed = np.zeros(int(1.5 * target)); fixed[: trimmed.size] = trimmed[: fixed.size]   # 4. pad to 1.5 s
shift = start / target                                   # 5. move the transcript with the audio
aligned = [(w, round(float(a - shift), 3), round(float(b - shift), 3)) for w, a, b in transcript]
print("fixed length:", fixed.size, "samples | transcript now:", aligned)
input: (97020, 2) at 44100 Hz = 2.2 s
mono, resampled: (35200,) at 16000 Hz = 2.2 s
trimmed to samples 8000 - 24000 = 1.0 s
fixed length: 24000 samples | transcript now: [('hello', 0.0, 1.0)]

The recording has 97,020 stereo samples (2.2 s at 44.1 kHz). Averaging the channels and resampling by the ratio 160/441 gives 35,200 mono samples at 16 kHz, still 2.2 s. The energy-based trim finds the word between samples 8,000 and 24,000, exactly 1.0 s, and the 1.5-second fixed length is reached with zero padding. Because 0.5 s was cut from the start, the transcript moves too: hello now runs from 0.0 to 1.0 s. Forgetting that step misaligns every label in a speech dataset by a different amount.

resample_poly applies an anti-aliasing low-pass filter before dropping samples. Plain slicing (audio[::3]) does not, and folds frequencies above the new Nyquist limit (half the sample rate) back into the audible range as artefacts.

Spectrograms and log-Mel features

A spectrogram cuts the signal into short overlapping frames (25 ms, every 10 ms is standard for speech) and takes the magnitude of the Fourier transform of each: time on one axis, frequency on the other. Human hearing resolves low frequencies finely and high ones coarsely, so speech and audio models usually pool the frequencies into Mel bands, triangular filters evenly spaced on the Mel scale (mel = 2595 * log10(1 + f / 700)), and take the logarithm of the energy, which matches perceived loudness. The result, a log-Mel spectrogram, is the standard input of speech and sound classifiers.

python · try it yourself
import numpy as np
from scipy.signal import stft
import matplotlib.pyplot as plt

sr = 16_000
t = np.arange(int(1.5 * sr)) / sr
rng = np.random.default_rng(1)
sweep = np.sin(2 * np.pi * (300 * t + 900 * t ** 2))     # pitch 300 Hz + 1800 Hz per second
audio = np.where(t < 1.2, sweep, 0) + 0.02 * rng.standard_normal(t.size)

f, frames, Z = stft(audio, fs=sr, nperseg=400, noverlap=240, nfft=512, boundary=None, padded=False)
power = np.abs(Z) ** 2                                   # (257 frequencies, frames)

def mel_filterbank(n_mels, n_fft, sr):
    hz_to_mel = lambda h: 2595 * np.log10(1 + h / 700)
    mel_to_hz = lambda m: 700 * (10 ** (m / 2595) - 1)
    edges = mel_to_hz(np.linspace(0, hz_to_mel(sr / 2), n_mels + 2))
    bins = np.fft.rfftfreq(n_fft, 1 / sr)
    fb = np.zeros((n_mels, bins.size))
    for m in range(n_mels):
        lo, mid, hi = edges[m], edges[m + 1], edges[m + 2]
        fb[m] = np.clip(np.minimum((bins - lo) / (mid - lo), (hi - bins) / (hi - mid)), 0, None)
    return fb, edges

fb, edges = mel_filterbank(40, 512, sr)
log_mel = 10 * np.log10(fb @ power + 1e-10)              # (40 bands, frames), in dB
print("spectrogram:", power.shape, "| log-Mel:", log_mel.shape)
print("frames per second:", round(len(frames) / 1.5, 1))
for sec in (0.1, 0.6, 1.1):
    k = int(np.argmin(np.abs(frames - sec)))
    band = int(np.argmax(log_mel[:, k]))
    print(f"t={sec:.1f}s: loudest band {band}, centre {edges[band + 1]:.0f} Hz")

fig, ax = plt.subplots(figsize=(6, 2.6))
ax.imshow(log_mel, origin="lower", aspect="auto", extent=[frames[0], frames[-1], 0, 40], cmap="magma")
ax.set_xlabel("time (s)"); ax.set_ylabel("Mel band"); ax.set_title("log-Mel spectrogram of a rising tone")
fig.tight_layout()
plt.show()
spectrogram: (257, 148) | log-Mel: (40, 148)
frames per second: 98.7
t=0.1s: loudest band 8, centre 517 Hz
t=0.6s: loudest band 17, centre 1416 Hz
t=1.1s: loudest band 23, centre 2360 Hz

With a 400-sample (25 ms) window and a 160-sample (10 ms) hop, the 1.5-second clip gives 148 frames, about 99 per second, each with 257 frequency bins; the filterbank pools them into 40 Mel bands. The loudest band follows the rising pitch: band 8 (centre 517 Hz) at 0.1 s, band 17 (1416 Hz) at 0.6 s, band 23 (2360 Hz) at 1.1 s, matching the tone's true frequencies of 480, 1380 and 2280 Hz to within one band. In the picture, the sweep is a rising line; the abrupt stop at 1.2 s shows up as a thin vertical stripe (a click spreads energy over all frequencies), followed by faint noise.

Libraries such as librosa and torchaudio compute the same thing in one call (librosa.feature.melspectrogram, torchaudio.transforms.MelSpectrogram); their default filter normalisation differs slightly, so use the same library for training and inference.

Noise: measure it before deciding

Noise is not always the enemy. If the model will run on phone recordings in the street, training on studio-clean audio is the real problem. Measure the signal-to-noise ratio of the clips, in decibels, SNR = 10 * log10(P_signal / P_noise), to see how varied the dataset is:

python · try it yourself
import numpy as np

rng = np.random.default_rng(2)
sr = 16_000
t = np.arange(sr) / sr
clean = 0.5 * np.sin(2 * np.pi * 220 * t)
power = lambda x: np.mean(x ** 2)

for name, noise_std in [("studio", 0.005), ("office", 0.05), ("street", 0.25)]:
    noise = noise_std * rng.standard_normal(t.size)
    snr = 10 * np.log10(power(clean) / power(noise))
    print(f"{name:7s} SNR {snr:5.1f} dB")

# Feature normalisation: statistics from the TRAINING clips only.
train_feats = rng.normal(-40, 12, (200, 40))             # 200 frames x 40 Mel bands (dB)
mu, sd = train_feats.mean(axis=0), train_feats.std(axis=0)
new_clip = rng.normal(-35, 12, (50, 40))
z = (new_clip - mu) / sd
print("normalised new clip: mean", round(float(z.mean()), 2), "std", round(float(z.std()), 2))
studio  SNR  37.0 dB
office  SNR  17.0 dB
street  SNR   3.1 dB
normalised new clip: mean 0.41 std 1.0

The three noise levels give 37.0, 17.0 and 3.1 dB: a 20 dB difference is a factor of 100 in power. A dataset that is all "studio" will not prepare a model for "street". The last line applies log-Mel statistics fitted on training frames to a new clip that is 5 dB louder on average: it comes out with mean 0.41 instead of 0, an honest sign of the shift, which is exactly what fitting on the training data alone should show.

Splits and leakage

The same speaker, the same recording session or overlapping windows cut from one long recording must stay on one side of the split. Cutting a 10-minute recording into 1-second windows and splitting the windows at random is the audio version of the time-series leak: neighbouring windows are almost identical. Split by recording, speaker or device (Split Strategies).

Pitfalls

  • Mixed sample rates: a model trained at 16 kHz fed 44.1 kHz audio hears everything at the wrong pitch and speed.
  • Downsampling by slicing: no anti-aliasing filter; use resample_poly or a library resampler.
  • Trimming without moving the labels: transcripts and event timestamps drift by exactly the trimmed amount.
  • Different feature code at inference: window, hop, number of Mel bands and filter normalisation must match training exactly.
  • Random splits of windows: split by recording, speaker or session.

Practice

  1. A 3-second clip recorded at 48 kHz is resampled to 16 kHz. How many samples does it have before and after, and what up/down would you pass to resample_poly?
Answer

144,000 samples before, 48,000 after; up=1, down=3.

  1. With 25 ms frames every 10 ms at 16 kHz, how many samples are in a frame and in a hop, and about how many frames does a 2-second clip give?
Answer

400 samples per frame, 160 per hop; (32,000 - 400) / 160 + 1 = 198.5, so 198 frames (a few more with padding at the edges).

Test yourself

Why is audio[::3] a bad way to go from 48 kHz to 16 kHz?

  1. It is too slow
  2. There is no anti-aliasing filter, so high frequencies fold back as artefacts
  3. It changes the number of channels
  4. It reverses the audio

You trim 0.4 s of leading silence from a clip. What must happen to its transcript timestamps?

  1. Nothing
  2. Subtract 0.4 s from every timestamp
  3. Add 0.4 s
  4. Multiply them by 0.4

What is a log-Mel spectrogram?

  1. The raw waveform in decibels
  2. Frame-wise spectra pooled into bands evenly spaced on the Mel scale, in log scale
  3. A list of words
  4. A histogram of sample values

A long recording is cut into 1-second windows. How should the windows be split into train and test?

  1. At random
  2. By recording (all windows of one recording on one side)
  3. By window loudness
  4. Alternating windows