◆ AI All-in-One

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
↗ Plan a path here

Read first

Tensors and Shapes

This leads to

Music and Voice GenerationSpeech Recognition
The full path from zero — 3 concepts before this one
  1. Vectors
  2. Matrices and Matrix Multiplication
  3. Tensors and Shapes
  4. Audio as Data

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.

Waveform (first 5 ms)440 Hz, amplitude 0.61000 Hz, amplitude 0.3their sum: what the microphone records+=time → Fouriertransform Spectrumamplitude of each frequency050010001500frequency (Hz)0.6 at 440 Hz0.3 at 1000 Hz
Fig. 1 Two pure tones (440 Hz and 1000 Hz) add up to the messy waveform a microphone records. The Fourier transform recovers the ingredients: two spikes at exactly those frequencies, with heights equal to their amplitudes.

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.

Waveformair pressure over timeSpectrogram01000200030004000Hz0 s0.5 s1.0 s1.5 stime →steady 440 Hz tonea rising whistle (chirp)800 Hz + 2400 Hz together darker = more energy at that frequency at that moment
Fig. 2 A synthetic 1.5-second recording and its spectrogram, computed with NumPy. The waveform barely hints at what is going on. The spectrogram shows a steady tone, a rising whistle, and two tones played together.

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 ff and amplitude AA is

x(t)=Asin⁡(2πft)x(t) = A \sin(2\pi f t)

where tt is time in seconds. The "2π2\pi" turns cycles into the angle that the sine function expects.

For a list of NN samples x0,x1,…,xN−1x_0, x_1, \dots, x_{N-1}, the discrete Fourier transform computes, for each frequency index kk, how strongly the signal matches a wave that completes kk cycles over the list:

Xk=∑n=0N−1xn e−2πikn/NX_k = \sum_{n=0}^{N-1} x_n \, e^{-2\pi i k n / N}

Read it as: multiply the signal by a test wave of frequency kk 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 e−2πikn/Ne^{-2\pi i kn/N} 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 ∣Xk∣|X_k| of each result, which is the amount of that frequency.

Index kk corresponds to the frequency k×sr/Nk \times \text{sr} / N hertz, where sr is the sample rate. So the frequency resolution is sr/N\text{sr}/N. One second of 16 kHz audio (N=16,000N = 16{,}000) gives bins 1 Hz apart. A 25 ms slice (N=400N = 400) gives bins 40 Hz apart.

Computing that sum directly for every kk takes about N2N^2 multiplications. The fast Fourier transform (FFT), published by Cooley and Tukey in 1965, gets the same answer in about Nlog⁡2NN \log_2 N. For N=16,000N = 16{,}000 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 0.6sin⁡(2π⋅440 t)+0.3sin⁡(2π⋅1000 t)0.6\sin(2\pi \cdot 440\,t) + 0.3\sin(2\pi \cdot 1000\,t), 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 2/N2/N, 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:

  1. Choose a frame length, the n_fft. For speech, 25 ms (400 samples at 16 kHz) is standard.
  2. Choose a hop, the step between frame starts. 10 ms (160 samples) is standard, so frames overlap.
  3. 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.
  4. Take the FFT of each frame and keep the squared magnitudes (the power).

One second of 16 kHz audio with these settings gives 1+(16,000−400)/160=981 + (16{,}000 - 400)/160 = 98 frames, each with 400/2+1=201400/2 + 1 = 201 frequency bins. Libraries usually pad the ends too, giving 101 frames. That 98×20198 \times 201 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):

dB=10log⁡10(power)\text{dB} = 10 \log_{10}(\text{power})

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

m=2595 log⁡10 ⁣(1+f700)m = 2595 \, \log_{10}\!\left(1 + \frac{f}{700}\right)

where ff is in hertz and mm 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 80×3,00080 \times 3{,}000 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 log⁡(0)\log(0) is −∞-\infty. 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

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

  1. 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.)
  2. Repeat the spectrogram with n_fft = 100 and then n_fft = 1600. How far apart are the frequency bins in each case, and how many frames do you get?
  3. 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.T with matplotlib.pyplot.imshow(..., origin="lower", aspect="auto").

Hint for 1: a tone at frequency ff above the Nyquist limit shows up at sr−f\text{sr} - f.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A speech model expects 16 kHz audio. What is the highest frequency that sample rate can represent?

  2. You downsample a recording by simply keeping every third sample. What can go wrong without anyone noticing?

  3. A model trained on 16 kHz audio is fed a 44.1 kHz file without resampling. What does it effectively hear?

  4. You compute a spectrogram with 25 ms frames. A colleague switches to 100 ms frames. What changes?

  5. Why is the power in a spectrogram usually converted to decibels before feeding a model?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Hugging Face Audio Course

Hugging Face · 2023 · Beginner · Free

A free hands-on course on audio with Transformers, from waveforms and spectrograms to audio classification, speech recognition with Whisper and text-to-speech.

Docs

librosa documentation

librosa developers · Intermediate · Free

The standard Python library for audio analysis. Its docs and examples cover loading, resampling, short-time Fourier transforms, mel spectrograms and MFCCs.

Book

Speech and Language Processing

Dan Jurafsky & James H. Martin · Intermediate · Free

The standard NLP textbook, kept up to date with chapters on Transformers and LLMs. Free drafts online.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/audio-basics.md