Level 3 In-Depth AI · Vision, Audio and Multimodal
Audio as Data
Sound reaches a computer as a long list of air-pressure measurements. The Fourier transform turns that list into frequencies, and a spectrogram shows how the frequencies change over time, which is the "image" most audio models actually look at.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 50 minutes to read, an hour to practise
- Builds on
- 3 concepts →
- Quiz
- 5 questions ↓
Read first
Tensors and ShapesThe full path from zero — 3 concepts before this one
Read them roughly in this order. See it on the concept map →
Why it matters
Voice assistants, automatic captions, meeting transcribers, music recommenders, bird-song identifiers and the voice mode of chat assistants all start from sound. Before any of them can do their job, a microphone recording has to become a tensor that a neural network can read.
Raw audio is awkward for models. One second of speech is 16,000 numbers, and the interesting structure (which notes, which vowels, which consonants) is hidden in how those numbers wiggle. The tools in this chapter (sampling, the Fourier transform and the spectrogram) turn that wiggle into a picture of which frequencies are present when. Most audio models, including OpenAI's Whisper for Speech Recognition, read such pictures. Once sound is a picture, ideas from vision such as convolutions and patch-based Transformers carry over almost unchanged.
The intuition
Sound is air pressure going up and down very quickly. A microphone measures that pressure thousands of times a second and writes down each measurement. The resulting list of numbers, plotted against time, is the waveform.
A pure musical note is a smooth, regular wave. The number of ups and downs per second is its frequency, measured in hertz (Hz). The A above middle C is 440 Hz. People hear roughly 20 Hz to 20,000 Hz. Real sounds, like a voice, a guitar or a car, are many such waves added together, which makes the waveform look messy.
Think of a chord on a piano. Your ear hears the individual notes even though they reach you as one combined pressure wave. The Fourier transform does the same thing mathematically: it takes the combined wave and tells you how much of each frequency is in it. The result is called a spectrum.
Speech and music change from moment to moment, so one spectrum for the whole recording is not enough. Instead, cut the recording into short overlapping slices (about 25 milliseconds each), take the spectrum of each slice, and line the spectra up side by side. The result is a spectrogram: time runs left to right, frequency runs bottom to top, and darkness shows how much energy there is.
Key idea Audio arrives as a 1-D list of pressure samples. A spectrogram turns it into a 2-D picture of frequency against time, and most audio models (including Whisper) read that picture, usually on a log-mel scale that mimics human hearing.
How it works
Sampling
A microphone produces a continuous voltage. An analogue-to-digital converter measures it at fixed intervals. The number of measurements per second is the sample rate:
- 44,100 Hz (44.1 kHz) for CDs and most music.
- 48,000 Hz for video.
- 16,000 Hz for most speech models. Whisper resamples everything to 16 kHz.
- 8,000 Hz for old telephone lines, which is why phone calls sound muffled.
Each measurement is typically stored as a 16-bit integer (values from −32,768 to 32,767). Libraries usually convert these to floats between −1 and 1. So ten seconds of 16 kHz mono speech is a 1-D tensor of 160,000 floats. Stereo audio has two channels and shape (2, samples).
How fast must you sample? The Nyquist frequency is half the sample rate, and it is the highest frequency a recording can represent. At 16 kHz that is 8,000 Hz, which covers the important parts of speech. At 44.1 kHz it is 22,050 Hz, just above human hearing, and that is why CDs use that rate. A frequency above the Nyquist limit doesn't simply vanish. It masquerades as a lower one, an effect called aliasing (the same effect makes car wheels seem to spin backwards in films). Proper resampling filters out the high frequencies first.
The Fourier transform
The central fact, due to Joseph Fourier in the early 1800s, is that any signal can be written as a sum of sine waves of different frequencies, amplitudes and starting points (phases). A single sine wave of frequency and amplitude is
where is time in seconds. The "" turns cycles into the angle that the sine function expects.
For a list of samples , the discrete Fourier transform computes, for each frequency index , how strongly the signal matches a wave that completes cycles over the list:
Read it as: multiply the signal by a test wave of frequency and add up the products. If the signal contains that frequency, the products line up and the sum is large. If it doesn't, they cancel out. The is a compact way of writing a cosine and a sine wave at once, using complex numbers. You don't need to manipulate complex numbers to use it. Just take the size of each result, which is the amount of that frequency.
Index corresponds to the frequency hertz, where sr is the sample rate. So the frequency resolution is . One second of 16 kHz audio () gives bins 1 Hz apart. A 25 ms slice () gives bins 40 Hz apart.
Computing that sum directly for every takes about multiplications. The fast Fourier transform (FFT), published by Cooley and Tukey in 1965, gets the same answer in about . For that is roughly 220,000 operations instead of 256 million. Every audio library uses the FFT.
Worked example. In the figure above, the signal is , sampled at 16 kHz for one second. The FFT gives 8,001 frequency bins, from 0 to 8,000 Hz in steps of 1 Hz. After scaling by , bin 440 has height 0.6, bin 1000 has height 0.3, and every other bin is essentially zero. The transform has recovered both notes and their volumes exactly.
The spectrogram
The short-time Fourier transform (STFT) applies the FFT to short, overlapping slices called frames:
- Choose a frame length, the
n_fft. For speech, 25 ms (400 samples at 16 kHz) is standard. - Choose a hop, the step between frame starts. 10 ms (160 samples) is standard, so frames overlap.
- Multiply each frame by a window, a bell-shaped curve such as the Hann window, which fades the edges to zero. Without it, the sharp cut at each end of a frame adds spurious frequencies.
- Take the FFT of each frame and keep the squared magnitudes (the power).
One second of 16 kHz audio with these settings gives frames, each with frequency bins. Libraries usually pad the ends too, giving 101 frames. That grid is the spectrogram.
There is a trade-off. Longer frames give finer frequency detail but blur fast events in time. Shorter frames do the reverse. You cannot have perfect precision in both at once. 25 ms is short enough to follow speech sounds and long enough to resolve the pitch of a voice.
Mel scale and decibels
Two more steps make spectrograms match how we hear.
First, loudness. We perceive loudness roughly on a logarithmic scale: ten times the power sounds about twice as loud, not ten times. So power is converted to decibels (dB):
Each step of 10 dB is a tenfold change in power. This also squeezes a huge range of values into a range that neural networks handle well.
Second, pitch. We hear the gap between 100 Hz and 200 Hz as large (an octave), but the gap between 7,000 Hz and 7,100 Hz as tiny. The mel scale (from "melody") stretches low frequencies and squeezes high ones so that equal steps in mels sound like equal steps in pitch. A common formula is
where is in hertz and in mels. It gives 150 mels for 100 Hz, 283 for 200 Hz, 1,000 for 1,000 Hz and 2,840 for 8,000 Hz. Below 1 kHz the scale is nearly linear, and above it nearly logarithmic.
A mel spectrogram sums the 201 FFT bins into a smaller number of overlapping triangular bands, typically 40 to 128, spaced evenly in mels. Taking the log gives the log-mel spectrogram, the standard input for speech and audio models. Whisper uses 80 mel bands (128 in its large-v3 version), 25 ms windows and a 10 ms hop. Thirty seconds of audio becomes an grid, a small greyscale image.
Older speech systems went one step further. Applying a cosine transform to each log-mel frame and keeping the first 13 or so coefficients gives MFCCs (mel-frequency cepstral coefficients). They are compact and were the standard input for decades. Neural networks today mostly use the log-mel spectrogram directly, or even the raw waveform.
In code
Everything above, from scratch in NumPy: build a two-tone signal, find its frequencies, compute a spectrogram and convert to mels.
import numpy as np
sr = 16_000 # sample rate: 16,000 samples per second
t = np.arange(sr) / sr # 1 second of time stamps
x = 0.6 * np.sin(2 * np.pi * 440 * t) + 0.3 * np.sin(2 * np.pi * 1000 * t)
print(x.shape, x[:4].round(3)) # (16000,) [0. 0.218 0.415 0.574]
# Fourier transform: which frequencies are present?
spectrum = np.abs(np.fft.rfft(x)) / (len(x) / 2) # amplitude of each frequency
freqs = np.fft.rfftfreq(len(x), d=1 / sr) # 0, 1, 2, ... 8000 Hz
top = np.argsort(spectrum)[-2:]
print(freqs[top], spectrum[top].round(3)) # [1000. 440.] [0.3 0.6]
# Spectrogram: FFT of short overlapping windows (25 ms long, every 10 ms)
n_fft, hop = 400, 160
window = np.hanning(n_fft)
frames = np.stack([x[i:i + n_fft] * window
for i in range(0, len(x) - n_fft + 1, hop)])
spec = np.abs(np.fft.rfft(frames, axis=1)) ** 2 # power, shape (frames, freqs)
print(frames.shape, spec.shape) # (98, 400) (98, 201)
log_spec = 10 * np.log10(spec + 1e-10) # decibels
print(np.fft.rfftfreq(n_fft, 1 / sr)[log_spec.mean(0).argmax()]) # 440.0
# Mel scale: equal steps in mel sound like equal steps in pitch
def hz_to_mel(f):
return 2595 * np.log10(1 + f / 700)
print(hz_to_mel(np.array([100, 200, 1000, 2000, 4000, 8000])).round(0))
# [ 150. 283. 1000. 1521. 2146. 2840.]
In practice you call a library. With librosa (speech.wav is any recording):
import librosa
y, sr = librosa.load("speech.wav", sr=16_000) # load and resample to 16 kHz, mono
mel = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=400, hop_length=160, n_mels=80)
log_mel = librosa.power_to_db(mel) # shape (80, frames)
Or with torchaudio, which runs inside PyTorch and on the GPU:
import torch
import torchaudio
wave = torch.sin(2 * torch.pi * 440 * torch.arange(16_000) / 16_000) # 1 s at 16 kHz
to_mel = torchaudio.transforms.MelSpectrogram(
sample_rate=16_000, n_fft=400, hop_length=160, n_mels=80)
log_mel = torchaudio.transforms.AmplitudeToDB()(to_mel(wave))
print(log_mel.shape) # torch.Size([80, 101])
Common pitfalls
- Wrong sample rate. A model trained on 16 kHz audio that receives 44.1 kHz audio hears everything about 2.75 times too slow and too low. Always resample to the rate the model expects, and check the rate your file loader returns.
- Stereo where mono is expected. A stereo file has shape (2, samples). Average the two channels (or pick one) before a mono model.
- Mismatched spectrogram settings.
n_fft, hop length, number of mel bands, the mel formula (librosa's default "Slaney" mel scale differs from the HTK formula above) and the log scaling all change the picture. A pretrained model needs exactly its own settings, so use its bundled feature extractor. - Log of zero. Silence gives zero power, and is . Add a small constant first, as in
spec + 1e-10. - Clipping. If a recording was too loud, samples get stuck at the maximum value. The flat-topped waveform adds harsh false frequencies that no model can undo.
- Confusing frames with seconds. With a 10 ms hop there are 100 frames per second. Time stamps from a model's output often have to be converted back.
Watch out Aliasing is silent. If you downsample by just taking every third sample, frequencies above the new Nyquist limit fold back into the range you keep and corrupt it. Use a proper resampler (
librosa.resample,torchaudio.functional.resample), which filters first.
Where it leads
- Speech Recognition turns log-mel spectrograms into text, with CTC-based models and with Whisper's encoder–decoder The Transformer.
- Convolutional networks and vision Transformers work on spectrograms as if they were images. The Audio Spectrogram Transformer does exactly that for sound classification.
- Data Augmentation for audio includes adding noise, shifting pitch and masking blocks of time or frequency in the spectrogram (SpecAugment).
- Music and Voice Generation runs the process in reverse, producing waveforms from text or from spectrograms.
- Multimodal language models feed audio features into a language model so it can listen as well as read.
A bit of history
Joseph Fourier presented his idea that heat flow, and by extension any periodic signal, can be written as a sum of sines in 1807, and published it in full in 1822. The sampling theorem behind the Nyquist limit is associated with Harry Nyquist (1928) and Claude Shannon (1949). James Cooley and John Tukey published the fast Fourier transform in 1965. Gauss had found essentially the same trick around 1805 but never published it in a form that caught on. The mel scale was proposed by Stevens, Volkmann and Newman in 1937, from experiments where listeners judged when pitches sounded equally far apart.
The spectrogram itself came from Bell Labs' "sound spectrograph" in the 1940s, a machine that burned frequency-against-time pictures of speech onto paper. Trained readers learned to read words from these pictures. Speech recognisers from the 1980s to the 2010s ran on MFCCs. Neural networks then shifted the input to log-mel spectrograms, the standard Whisper uses today.
Try it
- Change the second tone in the NumPy code from 1000 Hz to 9000 Hz, which is above the 8,000 Hz Nyquist limit. Which frequency does the FFT report now? (This is aliasing.)
- Repeat the spectrogram with
n_fft = 100and thenn_fft = 1600. How far apart are the frequency bins in each case, and how many frames do you get?- Harder: build a 3-second signal whose frequency rises from 200 Hz to 4,000 Hz (a chirp), compute its spectrogram, and plot
log_spec.Twithmatplotlib.pyplot.imshow(..., origin="lower", aspect="auto").Hint for 1: a tone at frequency above the Nyquist limit shows up at .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Hugging Face Audio Course
A free hands-on course on audio with Transformers, from waveforms and spectrograms to audio classification, speech recognition with Whisper and text-to-speech.
But what is the Fourier Transform? A visual introduction
A beautifully animated explanation of how the Fourier transform pulls the individual frequencies out of a mixed signal.
librosa documentation
The standard Python library for audio analysis. Its docs and examples cover loading, resampling, short-time Fourier transforms, mel spectrograms and MFCCs.
Speech and Language Processing
The standard NLP textbook, kept up to date with chapters on Transformers and LLMs. Free drafts online.
Robust Speech Recognition via Large-Scale Weak Supervision
Whisper: a Transformer trained on 680k hours of audio for robust speech recognition.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/audio-basics.md