Audio signals: STFT, spectrograms and the mel scale
Study digital sampling, STFT and time–frequency tradeoffs, log-mel and MFCC features, Griffin–Lim phase reconstruction, SpecAugment and audio classification.
After this lesson you can
- Implement STFT and its inverse with suitable windowing and overlap.
- Reason about temporal and frequency resolution when choosing a window.
- Build a mel filterbank and calculate log-mel spectrograms and MFCCs from scratch.
- Reconstruct magnitude-only signals with Griffin–Lim and explain phase.
- Train a log-mel audio classifier with SpecAugment.
Before you start
From pressure to samples
Spoken interaction starts with a pressure signal converted to voltage by a microphone. Digital audio represents it with samples and quantized levels. Sampling frequency defines Nyquist : components above it can fold into aliases unless filtered before sampling or resampling. Quantization introduces error and finite range can clip peaks. To change rate, use an antialias filter and record the actual rate rather than merely changing the header.
A moving FFT
The STFT multiplies each segment by a window and applies a DFT. For window , hop and FFT length ,
Centering and padding conventions change which samples belong to each frame. To invert, apply the inverse transform, multiply by the window again, and sum segments, dividing by the local sum of squared windows where positive. Padding covers the ends. A constant sum simplifies the formula but is unnecessary if normalizing pointwise with no zeros in the recovered region.
The time–frequency tradeoff arises because a long window observes more cycles and can separate nearby tones while spreading a brief event in time. Hop determines how often the window is evaluated, not its duration. Zero-padding reduces FFT grid frequency spacing but adds no observations and does not itself improve tone separation. Hann reduces leakage at the cost of a wider main lobe than a rectangular window.
From power to mel and coefficients
A mel spectrogram sums power through triangular filters spaced on an approximate perceptual scale. One convention is . The logarithm compresses dynamic range; a positive floor prevents silence producing infinities. Implementations differ in mel scale, filter normalization, amplitude versus power, and decibel reference: these are part of preprocessing.
MFCCs apply a DCT to log-mel and usually retain the first coefficients. Truncation summarizes the spectral envelope and discards detail. Current models often learn directly from log-mel; MFCCs remain useful in compact systems or classical models. Normalization statistics must be learned on training data only.
Phase matters too
Magnitude alone does not generally determine a unique waveform. Griffin–Lim alternates projection onto a consistent STFT and replacement with target magnitude, starting from an initial phase. Spectral consistency can improve without recovering original phase or guaranteeing good perceptual quality. Neural vocoders learn reconstruction but also depend on their data and conditions.
SpecAugment masks frequency bands and time spans during training. It can help with perturbations, but excessive masking removes the word; avoid applying it to validation or calculating statistics on test. A CNN processes local log-mel patterns; AST handles spectrotemporal patches with a transformer. Comparisons require declaring data, pretraining, budget, and noise.
Lab: reconstruction and features
The cell uses a synthetic signal, a 400-sample Hann window within a 512-point FFT, hop 160 and padding. It compares the custom STFT with SciPy after adjusting normalization; reconstructs with weighted overlap-add, calculates mel filters and 13 MFCCs, and measures relative magnitude difference after several iterations. This is a consistency measurement, not a speech score.
import numpy as np
from scipy.signal import stft as scipy_stft
from scipy.fft import dct
sr=16000;nfft=512;hop=160;win=np.zeros(nfft);win[56:456]=np.hanning(400)
def stft(x):
pad=nfft//2;z=np.pad(x,(pad,pad));extra=(- (len(z)-nfft))%hop;z=np.pad(z,(0,extra))
frames=np.stack([z[i:i+nfft]*win for i in range(0,len(z)-nfft+1,hop)])
return np.fft.rfft(frames,axis=1).T
def istft(X,length):
frames=np.fft.irfft(X.T,n=nfft,axis=1);size=(len(frames)-1)*hop+nfft;y=np.zeros(size);den=np.zeros(size)
for i,frame in enumerate(frames):
start=i*hop;y[start:start+nfft]+=frame*win;den[start:start+nfft]+=win**2
y=np.divide(y,den,out=np.zeros_like(y),where=den>1e-12)
return y[nfft//2:nfft//2+length]
def mel_filterbank(n_mels,n_fft,sr,fmin,fmax):
if not 0<=fmin<fmax<=sr/2:raise ValueError('rango inválido')
to_mel=lambda hz:2595*np.log10(1+hz/700)
hz=700*(10**(np.linspace(to_mel(fmin),to_mel(fmax),n_mels+2)/2595)-1);freq=np.fft.rfftfreq(n_fft,1/sr)
return np.maximum(0,np.minimum((freq[None,:]-hz[:-2,None])/(hz[1:-1,None]-hz[:-2,None]),(hz[2:,None]-freq[None,:])/(hz[2:,None]-hz[1:-1,None])))
def griffin_lim(magnitude,length,iterations,seed=27):
rng=np.random.default_rng(seed);phase=np.exp(2j*np.pi*rng.random(magnitude.shape));X=magnitude*phase
for _ in range(iterations):
estimate=stft(istft(X,length));phase=estimate/np.maximum(np.abs(estimate),1e-12);X=magnitude*phase
return istft(X,length)
t=np.arange(sr)/sr;x=.4*np.sin(2*np.pi*440*t)+.2*np.sin(2*np.pi*(500*t+700*t*t));x[6000:6010]+=.6
X=stft(x);recon=istft(X,len(x));pad=nfft//2;z=np.pad(x,(pad,pad));z=np.pad(z,(0,(-(len(z)-nfft))%hop))
_,_,ref=scipy_stft(z,fs=sr,window=win,nperseg=nfft,noverlap=nfft-hop,boundary=None,padded=False)
print('STFT forma:',X.shape,'error frente a scipy:',np.max(np.abs(X-ref*win.sum())))
print('error reconstrucción máxima:',np.max(np.abs(x-recon)))
bank=mel_filterbank(40,nfft,sr,0,sr/2);logmel=np.log(np.maximum(bank@(np.abs(X)**2),1e-10));mfcc=dct(logmel,type=2,axis=0,norm='ortho')[:13]
print('banco/logmel/MFCC:',bank.shape,logmel.shape,mfcc.shape,'valores finitos:',np.isfinite(mfcc).all())
mag=np.abs(X)
for n in (1,10,100):
y=griffin_lim(mag,len(x),n);m=np.abs(stft(y));print('Griffin-Lim',n,'error magnitud relativo:',round(float(np.linalg.norm(m-mag)/np.linalg.norm(mag)),5))Local lab: keywords
Use the ten words down, go, left, no, off, on, right, stop, up and yes from the Google Speech Commands v0.02 mirror, revision a751309c0fd613e8a5d30d77900f30e8b42bc2da. The run uses the first 100 available examples per class in training, 30 in validation and 50 in test, from the published splits. It checks that no speaker identifier occurs in two splits. Signals are padded or cropped to one second and 64 mel bands computed at 16 kHz. Mean and deviation are computed exclusively on training.
Noise comes from background examples labeled _silence_ in test, selected with a fixed seed and scaled to 10 dB RMS signal-to-noise ratio before addition. A small CNN and compact transformer are trained from scratch on spectrogram patches, with or without one frequency and one time mask. This SpecAugment variant omits the original paper’s time warping. The transformer is an educational AST-inspired implementation, not the paper’s checkpoint or full architecture. Each model trains five epochs with the same seed; selection is not based on test. The following measurement used CPU with PyTorch and torchaudio 2.11 and is a limited sample, not a complete benchmark:
| Model | Parameters | Clean test, correct/500 | Noisy test, correct/500 |
|---|---|---|---|
| CNN | 39018 | 68 | 51 |
| CNN + SpecAugment | 39018 | 66 | 49 |
| Compact transformer | 165994 | 131 | 49 |
| Compact transformer + SpecAugment | 165994 | 106 | 51 |
Clean accuracy is low and noise especially degrades the transformer without augmentation. Augmentation shows no conclusive improvement in this trial; more data, training, and seeds are needed to estimate its effect. Code prints validation history and hashes of the eight downloaded files. When CUDA is available it computes log-mel and trains on GPU; SPEECH_CPU=1 reproduces the CPU measurement protocol. The first download occupies several gigabytes. Install torch, torchaudio, numpy, scipy, pyarrow and huggingface_hub in a compatible environment.
import io, os, json, hashlib, time
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
from scipy.io import wavfile
import torch
from torch import nn
import torchaudio
from huggingface_hub import hf_hub_download
# The Parquet mirror is pinned; use its official split and record every input hash.
REV='a751309c0fd613e8a5d30d77900f30e8b42bc2da'
WORDS=('down','go','left','no','off','on','right','stop','up','yes')
root=Path(os.environ.get('SPEECH_ROOT','speech-commands-data'))
counts={'train':100,'validation':30,'test':50}
counts={k:int(os.environ.get('SPEECH_'+k.upper(),v)) for k,v in counts.items()}
epochs=int(os.environ.get('SPEECH_EPOCHS','5'))
device='cuda' if torch.cuda.is_available() and os.environ.get('SPEECH_CPU')!='1' else 'cpu'
torch.set_num_threads(2);torch.manual_seed(27);np.random.seed(27)
files={}
for split in counts:
names=[f'train-{i:05d}-of-00006.parquet' for i in range(6)] if split=='train' else [f'{split}-00000-of-00001.parquet']
files[split]=[Path(hf_hub_download('google/speech_commands',repo_type='dataset',revision=REV,filename='v0.02/'+n,local_dir=root)) for n in names]
def digest(p):
with p.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
hashes={str(p.name):digest(p) for paths in files.values() for p in paths}
def decode(blob):
sr,a=wavfile.read(io.BytesIO(blob));assert sr==16000
if a.ndim==2:a=a.mean(1)
a=a.astype('float32')/32768 if np.issubdtype(a.dtype,np.integer) else a.astype('float32')
return np.pad(a[:16000],(0,max(0,16000-len(a))))
def load(split):
groups={w:[] for w in WORDS};noise=[];speakers=set()
for path in files[split]:
for batch in pq.ParquetFile(path).iter_batches(batch_size=128,columns=['file','audio','speaker_id']):
for row in batch.to_pylist():
word=row['file'].split('/')[0]
if word in groups and len(groups[word])<counts[split]:
groups[word].append(decode(row['audio']['bytes']));speakers.add(row['speaker_id'])
elif split=='test' and word=='_silence_' and len(noise)<100:
noise.append(decode(row['audio']['bytes']))
if all(len(v)==counts[split] for v in groups.values()) and (split!='test' or len(noise)>=100):break
if all(len(v)==counts[split] for v in groups.values()) and (split!='test' or len(noise)>=100):break
assert all(len(v)==counts[split] for v in groups.values()), {k:len(v) for k,v in groups.items()}
x=np.stack([a for w in WORDS for a in groups[w]]);y=np.repeat(np.arange(len(WORDS)),counts[split])
print(split,'samples',len(y),'speakers',len(speakers),'noise',len(noise),flush=True)
return torch.from_numpy(x),torch.from_numpy(y),speakers,noise
train_x,train_y,train_s,_=load('train');val_x,val_y,val_s,_=load('validation');test_x,test_y,test_s,noise=load('test')
print('speaker intersections train/validation/test',len(train_s&val_s),len(train_s&test_s),len(val_s&test_s),flush=True)
assert not (train_s&val_s or train_s&test_s or val_s&test_s)
assert noise
gen=torch.Generator().manual_seed(271)
noise=torch.from_numpy(np.stack(noise));picked=noise[torch.randint(len(noise),(len(test_x),),generator=gen)]
signal_rms=test_x.square().mean(1,keepdim=True).sqrt();noise_rms=picked.square().mean(1,keepdim=True).sqrt().clamp_min(1e-8)
noisy_x=test_x+picked/noise_rms*signal_rms/(10**(10/20))
mel=torchaudio.transforms.MelSpectrogram(sample_rate=16000,n_fft=400,hop_length=160,n_mels=64).to(device)
def features(x):
out=[]
with torch.no_grad():
for part in x.split(64):out.append(torch.log(mel(part.to(device)).clamp_min(1e-6)).cpu())
return torch.cat(out)
tr=features(train_x);va=features(val_x);te=features(test_x);no=features(noisy_x)
mean,std=tr.mean(),tr.std().clamp_min(1e-6)
tr=(tr-mean)/std;va=(va-mean)/std;te=(te-mean)/std;no=(no-mean)/std
print('log-mel',tuple(tr.shape),'train mean/std',float(mean),float(std),'device',device,flush=True)
if os.environ.get('SPEECH_PREP_ONLY')=='1':raise SystemExit
class CNN(nn.Module):
def __init__(self):
super().__init__();self.net=nn.Sequential(nn.Conv2d(1,24,3,padding=1),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(24,48,3,padding=1),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(48,64,3,padding=1),nn.ReLU(),nn.AdaptiveAvgPool2d(1),nn.Flatten(),nn.Linear(64,10))
def forward(self,x):return self.net(x[:,None])
class ASTCompact(nn.Module):
def __init__(self):
super().__init__();self.patch=nn.Conv2d(1,96,(8,10),stride=(8,10));self.position=nn.Parameter(torch.zeros(1,80,96));self.encoder=nn.TransformerEncoder(nn.TransformerEncoderLayer(96,4,192,dropout=.1,batch_first=True,norm_first=True),2);self.head=nn.Linear(96,10)
def forward(self,x):
h=self.patch(x[:,None]).flatten(2).transpose(1,2);return self.head(self.encoder(h+self.position).mean(1))
def augment(x):
x=x.clone()
for i in range(len(x)):
f=int(torch.randint(0,9,(1,)));t=int(torch.randint(0,13,(1,)))
fs=int(torch.randint(0,x.shape[1]-f+1,(1,)));ts=int(torch.randint(0,x.shape[2]-t+1,(1,)))
x[i,fs:fs+f,:]=0;x[i,:,ts:ts+t]=0
return x
def accuracy(model,x,y):
model.eval();pred=[]
with torch.no_grad():
for part in x.split(64):pred.append(model(part.to(device)).argmax(1).cpu())
return float((torch.cat(pred)==y).float().mean())
results={}
for kind,cls in [('CNN',CNN),('AST compacto',ASTCompact)]:
for aug in (False,True):
torch.manual_seed(27);model=cls().to(device);optimizer=torch.optim.AdamW(model.parameters(),lr=.001);hist=[]
for epoch in range(epochs):
model.train();perm=torch.randperm(len(tr));loss_sum=0.
for ids in perm.split(32):
x=tr[ids].to(device);x=augment(x) if aug else x;y=train_y[ids].to(device)
loss=nn.functional.cross_entropy(model(x),y);optimizer.zero_grad();loss.backward();optimizer.step();loss_sum+=float(loss.detach())*len(ids)
val=accuracy(model,va,val_y);hist.append({'epoch':epoch+1,'loss':loss_sum/len(tr),'validation_accuracy':val})
print(kind,'SpecAugment',aug,'epoch',epoch+1,'loss',round(hist[-1]['loss'],4),'validation',round(val,4),flush=True)
results[kind+(' + SpecAugment' if aug else ' sin aumento')]={'parameters':sum(p.numel() for p in model.parameters()),'history':hist,'test_clean':accuracy(model,te,test_y),'test_noise_10db':accuracy(model,no,test_y)}
print(kind,aug,results[kind+(' + SpecAugment' if aug else ' sin aumento')],flush=True)
output=Path(os.environ.get('SPEECH_OUTPUT',str(root/'results.json')));output.parent.mkdir(parents=True,exist_ok=True)
output.write_text(json.dumps({'revision':REV,'sha256':hashes,'counts_per_class':counts,'epochs':epochs,'classes':WORDS,'noise':'held-out Speech Commands _silence_, 10 dB SNR by RMS','results':results},indent=2),encoding='utf8')
npm run lab and open the connection link.Exercises
Step 1 of 3. What sum is obtained at a sample?
import numpy as np
def mel_filterbank(n_mels,n_fft,sr,fmin,fmax):
passSources: Griffin and Lim, SpecAugment, AST and Speech and Language Processing.