Skip to content

Spectrograms and mel features: every setting is part of the data

Most audio models read a log-mel spectrogram, not the waveform. See how the window, hop, mel bank and log floor shape it, why a model trained on one convention fails on another, and compute a spectrogram by hand in Python and R.

Introductory ~14 min8 steps

What runs in CodeSplash

You will be able to

  • Compute a short-time Fourier transform and read its frames and frequency bins
  • Explain the time–frequency trade-off of the window length
  • Describe the mel filterbank, the log floor and MFCCs
  • List the settings a spectrogram must carry so another model can read it

Read first

01

Slices of sound

Read

A waveform says how loud the air was at each instant, not which pitches were sounding. The short-time Fourier transformShort-time Fourier transform (STFT)A sound cut into short overlapping windowed frames, each turned into frequencies: the basis of spectrograms and most audio features. answers that slice by slice. Cut the signal into overlapping frames, taper each one with a window functionWindow functionComputes across a set of related rows while keeping every row, whereas GROUP BY collapses them., and take its Fourier transform. The magnitudes, frames side by side, form a spectrogramSpectrogramA picture of sound: time across, frequency up, brightness for level; tones are lines, noise is a wash, clicks are vertical stripes..

Three numbers define it: the frame length (the FFT size), the hop between frame starts, and the window shape. Each changes the picture, so each belongs with the data.

02

Compute one by hand

Read

One second of a 440 Hz tone at 16 kHz, frames of 512 samples, a hop of 160 samples:

Python
import numpy as np
sr, n_fft, hop = 16000, 512, 160
t = np.arange(sr) / sr                       # one second
x = np.sin(2 * np.pi * 440 * t)              # a 440 Hz tone
win = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n_fft) / n_fft)   # periodic Hann
n_frames = 1 + (len(x) - n_fft) // hop       # no padding at the ends
frames = np.stack([x[i * hop:i * hop + n_fft] * win for i in range(n_frames)])
S = np.abs(np.fft.rfft(frames, axis=1))      # frames x frequency bins
print(n_frames, S.shape[1], S.mean(0).argmax() * sr / n_fft)
R
sr <- 16000; n_fft <- 512; hop <- 160
t <- (0:(sr - 1)) / sr                       # one second
x <- sin(2 * pi * 440 * t)                   # a 440 Hz tone
win <- 0.5 - 0.5 * cos(2 * pi * (0:(n_fft - 1)) / n_fft)   # periodic Hann
n_frames <- 1 + (length(x) - n_fft) %/% hop  # no padding at the ends
S <- sapply(0:(n_frames - 1), function(i) Mod(fft(x[i * hop + 1:n_fft] * win))[1:(n_fft / 2 + 1)])
print(c(n_frames, nrow(S), (which.max(rowMeans(S)) - 1) * sr / n_fft))

Bins sit 16000/51216000/512 Hz apart, so the peak lands on the bin nearest 440 Hz, not on 440 itself. Both languages print the same three numbers.

03

The window trade-off

Predict

Predict first

You double the frame length from 512 to 1,024 samples and keep the hop. What happens to the spectrogram?

Sharper in both time and frequencySharper in frequency, blurrier in timeSharper in time, blurrier in frequency
Reveal

Sharper in frequency, blurrier in time. Bins get twice as close, but each frame now averages twice as much time, so a quick click or a syllable onset smears. No single length is right: speech features often use frames of 20–40 ms; music analysis uses longer ones.

04

Mel bands and the log

Read

Hearing resolves low pitches finely and high pitches coarsely. A mel filterbank imitates that: triangular filters, narrow at low frequencies and wide at high ones, each adding up the bins under it. On the mel scaleMel scaleA pitch scale spaced the way people hear: about linear below 1 kHz, logarithmic above. Mel bands pool a spectrum into it., a few dozen bands replace hundreds of bins.

Then take the log, because loudness is heard roughly on a log scale. A silent bin would give minus infinity, so the values are clamped at a log floorLog floor (spectrogram)The small value a spectrogram is clamped to before taking its log, so silent bins don't become minus infinity. first. The floor decides how quiet sounds look. MFCCsMFCC (mel-frequency cepstral coefficients)A few numbers per frame describing the overall shape of the spectrum (timbre): the DCT of the log mel spectrum. go one step further: a cosine transform of the log-mel frame, keeping the first coefficients as a summary of the spectral shape.

AExplorable · Spectrograms: window, hop, mel bands and the log floor

Why can't one spectrogram be sharp in both time and frequency?

The tones are 100 Hz apart. With this window, will they show as two lines?

How sure?

Sound

Two tones 100 Hz apart with a click halfway, a rising chirp, or a sung vowel.

Window length (samples)

Longer windows separate close frequencies but smear sounds in time. 8,000 samples per second.

Hop

How far the window moves between frames, as a share of its length.

Window shape

Hann and Hamming taper the edges; a rectangular window cuts them off and leaks energy into every bin.

32

Triangular filters spaced evenly on the mel scale: narrow at low pitch, wide at high pitch.

80

Anything quieter is drawn at the floor. A deeper floor shows faint detail and noise alike.

Show

The power spectrogram on a linear frequency axis, or the same power summed into mel bands.

Bins 62.5 Hz apart, window 16 ms, hop 4.0 ms. Orange ticks and lines mark the two tones.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

05

Same shape, different data

Read

Two log-mel matrices can have the same shape and mean different things. Power or magnitude, natural log or decibels, the floor, the mel formula (Slaney or HTK), the lowest and highest frequency, centered or not: change any one and a model trained on the other convention reads nonsense. A vocoder fed mels from another recipe buzzes; a recognizer fed the wrong floor hears noise as speech.

That is why the spectrogram data contractData contract: spectrogramsFrequency × time pictures of sound: record the window, hop, mel bins and log floor, and fit normalization on training recordings. asks for every setting, and why CodeSplash computes Whisper's log-mel exactly as Whisper's own code does.

06

Features in CodeSplash

Read
Audio features (MFCC, spectral shape, chroma, loudness)Recorded · Python and R agreeRecorded 2026-11-25 · 47 values compared · largest relative difference 3.8e-15
R

7 files described by 39 features in 7 rows.

Files read
7
Rows in the table
7
Features
39

Assumptions

  • Files decode — 2 of 9 listed files could not be read.
  • One sample rate — Every file was resampled to 16000 Hz and mixed to mono.
  • Summaries lose order — Each file is summarized as a whole; turn on windows to keep time.

Feature table (first rows and columns)

media_idpathfilelabelmfcc_1_meanmfcc_1_sdmfcc_2_meanmfcc_2_sdmfcc_3_meanmfcc_3_sdmfcc_4_meanmfcc_4_sd
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone−371.2946.88849.61729.65031.09118.45412.7867.417
2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920aud1_clips/tone_b.wavtone_b.wavtone−226.7418.63126.96614.5448.3123.411−12.1512.866
0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5aud1_clips/noise_a.wavnoise_a.wavnoise−209.813.530137.255.598−27.5483.239−1.6403.268
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp−171.7223.80749.76225.357−54.39921.88820.51922.270
600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891aud1_clips/quiet.wavquiet.wavtone−548.8827.25263.25011.11751.5106.59635.2285.031
399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84aud1_clips/silence.wavsilence.wavsilence−632.465.684e-131.332e-1506.795e-140−5.773e-140
4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485aud1_clips/speechlike.wavspeechlike.wavspeech−272.4033.52725.96740.32917.86224.8347.47910.073

Files that could not be read

FilePath
notes.wavaud1_clips/notes.wav
not_there.wavaud1_clips/not_there.wav
  • 2 listed files could not be read and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Audio features (MFCC, spectral shape, chroma, loudness)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.features 1.0.0 · spec e62c9082764ccfee
# Dataset: aud1_clips (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud1_clips.parquet", col_select = c("path", "label")))
n_input <- nrow(df)
df[["path"]] <- factor(df[["path"]], levels = sort(unique(df[["path"]]), method = "radix"))
df[["label"]] <- factor(df[["label"]], levels = sort(unique(df[["label"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("path", "label")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("path", "label"))  # infinite values stop the run (registry/errors.yaml)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-8142/audio.features/files_defaults/out-r", df,
                        "tests/parity/fixtures/aud1_clips.parquet")
media_ids <- cs_media_ids(media, df)
if (is.null(media$root) || !nzchar(media$root)) {
  media$root <- dirname(normalizePath("tests/parity/fixtures/aud1_clips.parquet", mustWork = FALSE))  # relative paths start next to the data file
}

# %% Settings
PATH <- "path"
LABEL <- "label"
SR <- as.numeric(media$transform$sample_rate)
on <- c(mfcc = TRUE, spectral = TRUE, chroma = FALSE,
        energy = TRUE, loudness = TRUE)
SETS <- names(on)[on]
STATS <- list(mean_sd = c("mean", "sd"), mean = "mean", all = c("mean", "sd", "min", "max"))[["mean_sd"]]
N_MFCC <- 13; N_MELS <- 40; N_FFT <- 512; HOP <- 160
PER_WINDOW <- FALSE
WIN <- 1; WIN_HOP <- 0.5
if (!length(SETS)) cs_error("CS_E_INVALID_OPTION", option = "Features", allowed = "at least one feature set", value = "none")
if ("mfcc" %in% SETS && N_MFCC > N_MELS) {
  cs_error("CS_E_INVALID_OPTION", option = "Number of MFCCs", allowed = sprintf("at most the number of mel bands (%d)", N_MELS), value = N_MFCC)
}
FEATURES <- cs_audio_feature_columns(SETS, STATS, N_MFCC)

# %% Features per file (or per window)
status <- cs_media_status(media, media_ids)
paths <- as.character(df[[PATH]])
labels <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
rows <- list(); bad <- list(); first <- NULL
for (i in seq_along(media_ids)) {
  x <- NULL
  if (is.na(status[i])) x <- tryCatch(as.numeric(cs_media_audio(media, media_ids[i])[[1]]), cs_error = function(e) NULL)
  if (is.null(x)) {
    bad[[length(bad) + 1]] <- list(file = basename(paths[i]), path = paths[i])
    next
  }
  if (is.null(first)) first <- list(name = basename(paths[i]), x = x)
  spans <- if (PER_WINDOW) cs_audio_windows(length(x), SR, WIN, WIN_HOP) else matrix(c(0, length(x)), ncol = 2)
  for (w in seq_len(nrow(spans))) {
    a <- spans[w, 1]; b <- spans[w, 2]
    rows[[length(rows) + 1]] <- list(media_id = media_ids[i], path = paths[i], file = basename(paths[i]),
                                     label = if (!is.null(labels)) labels[i] else NULL,
                                     window = w - 1L, start_s = a / SR, end_s = b / SR,
                                     f = cs_audio_clip_row(x[(a + 1):b], SR, SETS, STATS, N_FFT, HOP, N_MELS, N_MFCC))
  }
}
if (!length(rows)) cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an audio file that exists and can be decoded", count = length(media_ids))
if (length(bad)) warnings <- c(warnings, sprintf("%d listed files could not be read and are left out.", length(bad)))

# %% Artifact: the feature table (save it as a dataset)
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.features/files_defaults/out-r")
Fm <- do.call(rbind, lapply(rows, function(r) r$f))
if (!is.matrix(Fm)) Fm <- matrix(Fm, nrow = length(rows))
art <- data.frame(media_id = vapply(rows, function(r) r$media_id, ""), path = vapply(rows, function(r) r$path, ""),
                  file = vapply(rows, function(r) r$file, ""), stringsAsFactors = FALSE)
if (!is.null(labels)) art$label <- vapply(rows, function(r) r$label, "")
if (PER_WINDOW) {
  art$window <- vapply(rows, function(r) as.integer(r$window), 0L)
  art$start_s <- vapply(rows, function(r) r$start_s, 0)
  art$end_s <- vapply(rows, function(r) r$end_s, 0)
}
for (j in seq_along(FEATURES)) art[[FEATURES[j]]] <- ifelse(is.nan(Fm[, j]), NA_real_, Fm[, j])
NAME <- if (PER_WINDOW) "windows" else "features"
art_path <- file.path(out, paste0(NAME, ".parquet"))
nanoparquet::write_parquet(art, art_path)

# %% Result
n_files <- length(media_ids) - length(bad)
values <- list(n_rows = length(media_ids), n_files = n_files, n_unreadable = length(bad), n_out_rows = length(rows), n_features = length(FEATURES),
               sample_rate = SR, frame_ms = 1000 * N_FFT / SR, hop_ms = 1000 * HOP / SR)
for (c in FEATURES) {
  v <- art[[c]]
  v <- v[is.finite(v)]
  if (length(v)) values[[sprintf("mean[%s]", c)]] <- mean(v)
}
lead <- c("media_id", "path", "file", if (!is.null(labels)) "label", if (PER_WINDOW) c("window", "start_s", "end_s"))
show <- c(lead, FEATURES[seq_len(min(8, length(FEATURES)))])
nf <- function(v) if (is.numeric(v) && !is.finite(v)) NULL else v
preview <- lapply(seq_len(min(25, nrow(art))), function(i) stats::setNames(lapply(show, function(k) nf(art[[k]][i])), show))
tables <- list(list(key = "features", title = "Feature table (first rows and columns)",
                    columns = lapply(show, function(k) if (k %in% c(FEATURES, "start_s", "end_s")) list(key = k, label = k, type = "number") else list(key = k, label = k)),
                    rows = preview))
if (length(bad)) {
  tables[[2]] <- list(key = "unreadable", title = "Files that could not be read", columns = list(list(key = "file", label = "File"), list(key = "path", label = "Path")),
                      rows = bad[seq_len(min(50, length(bad)))])
}
seg <- first$x[seq_len(as.integer(min(length(first$x), 10 * SR)))]
M <- cs_audio_power_to_db(cs_audio_mel_spectrogram(seg, SR, N_FFT, HOP, N_MELS), "max", 1e-10, 80)
mel_hz <- cs_audio_mel_frequencies(N_MELS + 2, 0, SR / 2)[2:(N_MELS + 1)]
T <- cs_audio_frame_times(ncol(M), SR, HOP)
charts <- list(cs_chart("spectrogram", "spectrogram", paste0("Mel spectrogram: ", first$name), list(
  x = cs_col("Time (s)", rep(T, each = N_MELS), "numeric"),
  y = cs_col("Frequency (Hz, mel band center)", rep(mel_hz, length(T)), "numeric"),
  z = cs_col("Level (dB re max)", as.vector(M), "numeric")
), controls = list(scale = "mel"), note = sprintf("Hann frames of %d samples every %d at %d Hz, %d Slaney mel bands, dB relative to the loudest cell (floor −80 dB).", N_FFT, HOP, as.integer(SR), N_MELS)))
pair <- if ("mfcc_2_mean" %in% FEATURES) c("mfcc_1_mean", "mfcc_2_mean") else if (all(c("centroid_mean", "rms_mean") %in% FEATURES)) c("centroid_mean", "rms_mean") else NULL
if (!is.null(pair)) {
  roles <- list(x = cs_col(pair[1], art[[pair[1]]], "numeric"), y = cs_col(pair[2], art[[pair[2]]], "numeric"))
  if (!is.null(labels)) roles$color <- cs_col(LABEL, art$label, "categorical", head(levels(df[[LABEL]]), 8))
  charts[[2]] <- cs_chart("map", "scatter", if (PER_WINDOW) "Windows by their first two features" else "Files by their first two features", roles, controls = list(fit = "none"))
}
assumptions <- list(
  list(key = "decoded", label = "Files decode", status = if (length(bad)) "warn" else "pass",
       detail = if (length(bad)) sprintf("%d of %d listed files could not be read.", length(bad), length(media_ids)) else "Every listed file was decoded."),
  list(key = "same_rate", label = "One sample rate", status = "info", detail = sprintf("Every file was resampled to %d Hz and mixed to mono.", as.integer(SR))),
  list(key = "summary_loses_order", label = "Summaries lose order", status = "info",
       detail = if (PER_WINDOW) "Each window is summarized on its own." else "Each file is summarized as a whole; turn on windows to keep time.")
)
cs_publish(list(
  title = "Audio features (MFCC, spectral shape, chroma, loudness)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = n_files,
  summary = sprintf("%d files described by %d features in %d rows.", n_files, length(FEATURES), length(rows)),
  statistics = list(
    list(key = "n_files", label = "Files read", value = n_files),
    list(key = "n_out_rows", label = "Rows in the table", value = length(rows)),
    list(key = "n_features", label = "Features", value = length(FEATURES))
  ),
  tables = tables,
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = paste0("factors_", NAME), path = art_path, format = "parquet"))
))
Python

7 files described by 39 features in 7 rows.

Files read
7
Rows in the table
7
Features
39

Assumptions

  • Files decode — 2 of 9 listed files could not be read.
  • One sample rate — Every file was resampled to 16000 Hz and mixed to mono.
  • Summaries lose order — Each file is summarized as a whole; turn on windows to keep time.

Feature table (first rows and columns)

media_idpathfilelabelmfcc_1_meanmfcc_1_sdmfcc_2_meanmfcc_2_sdmfcc_3_meanmfcc_3_sdmfcc_4_meanmfcc_4_sd
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone−371.2946.88849.61729.65031.09118.45412.7867.417
2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920aud1_clips/tone_b.wavtone_b.wavtone−226.7418.63126.96614.5448.3123.411−12.1512.866
0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5aud1_clips/noise_a.wavnoise_a.wavnoise−209.813.530137.255.598−27.5483.239−1.6403.268
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp−171.7223.80749.76225.357−54.39921.88820.51922.270
600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891aud1_clips/quiet.wavquiet.wavtone−548.8827.25263.25011.11751.5106.59635.2285.031
399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84aud1_clips/silence.wavsilence.wavsilence−632.4601.332e-1506.795e-140−5.773e-140
4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485aud1_clips/speechlike.wavspeechlike.wavspeech−272.4033.52725.96740.32917.86224.8347.47910.073

Files that could not be read

FilePath
notes.wavaud1_clips/notes.wav
not_there.wavaud1_clips/not_there.wav
  • 2 listed files could not be read and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Audio features (MFCC, spectral shape, chroma, loudness)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.features 1.0.0 · spec e62c9082764ccfee
# Dataset: aud1_clips (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import dsp
from codesplash.audio import features as af
from codesplash.errors import CsError

# %% Data
df = pd.read_parquet("tests/parity/fixtures/aud1_clips.parquet", columns=["path", "label"])
n_input = len(df)
df["path"] = pd.Categorical(df["path"], categories=sorted(df["path"].dropna().unique()))
df["label"] = pd.Categorical(df["label"], categories=sorted(df["label"].dropna().unique()))
df = df.dropna(subset=["path", "label"])  # listwise deletion over the analysis columns
df["path"] = df["path"].cat.remove_unused_categories()
df["label"] = df["label"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["path", "label"])  # infinite values stop the run (registry/errors.yaml)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-8142/audio.features/files_defaults/out-python", df, "tests/parity/fixtures/aud1_clips.parquet")
media_ids = cs_media.ids_of(media, df)
if not media.get("root"):
    media["root"] = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud1_clips.parquet"))  # relative paths start next to the data file

# %% Settings
PATH = "path"
LABEL = "label"
SR = float(media["transform"]["sample_rate"])
SETS = [s for s, on in (("mfcc", True), ("spectral", True), ("chroma", False),
                        ("energy", True), ("loudness", True)) if on]
STATS = {"mean_sd": ["mean", "sd"], "mean": ["mean"], "all": ["mean", "sd", "min", "max"]}["mean_sd"]
N_MFCC, N_MELS, N_FFT, HOP = 13, 40, 512, 160
PER_WINDOW = False
WIN, WIN_HOP = 1, 0.5
if not SETS:
    cs.cs_error("CS_E_INVALID_OPTION", option="Features", allowed="at least one feature set", value="none")
if "mfcc" in SETS and N_MFCC > N_MELS:
    cs.cs_error("CS_E_INVALID_OPTION", option="Number of MFCCs", allowed=f"at most the number of mel bands ({N_MELS})", value=N_MFCC)
FEATURES = af.column_names(SETS, STATS, N_MFCC)

# %% Features per file (or per window)
status = cs_media.status(media, media_ids)
paths = df[PATH].astype(str).tolist()
labels = df[LABEL].astype(str).tolist() if LABEL is not None else None
rows, bad, first = [], [], None
for i, mid in enumerate(media_ids):
    x = None
    if status[i] is None:
        try:
            x = np.asarray(cs_media.audio(media, [mid])[0], dtype=np.float64)
        except CsError:
            x = None
    if x is None:
        bad.append({"file": os.path.basename(paths[i]), "path": paths[i]})
        continue
    if first is None:
        first = (os.path.basename(paths[i]), x)
    base = {"media_id": mid, "path": paths[i], "file": os.path.basename(paths[i])}
    if labels is not None:
        base["label"] = labels[i]
    spans = af.windows(len(x), SR, WIN, WIN_HOP) if PER_WINDOW else [(0, len(x))]
    for w, (a, b) in enumerate(spans):
        rec = dict(base)
        if PER_WINDOW:
            rec.update(window=w, start_s=a / SR, end_s=b / SR)
        rec.update(zip(FEATURES, af.clip_row(x[a:b], SR, SETS, STATS, N_FFT, HOP, N_MELS, N_MFCC)))
        rows.append(rec)
if not rows:
    cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an audio file that exists and can be decoded", count=len(media_ids))
warnings = list(warnings)
if bad:
    warnings.append(f"{len(bad)} listed files could not be read and are left out.")

# %% Artifact: the feature table (save it as a dataset)
out = csml.out_dir("target/academy-parity/run-8142/audio.features/files_defaults/out-python")
keys = ["media_id", "path", "file"] + (["label"] if labels is not None else []) + (["window", "start_s", "end_s"] if PER_WINDOW else []) + FEATURES
art = pd.DataFrame(rows, columns=keys)
for c in ("media_id", "path", "file", "label"):
    if c in art:
        art[c] = art[c].astype("string")
if PER_WINDOW:
    art["window"] = art["window"].astype("int64")
for c in FEATURES:
    art[c] = pd.to_numeric(art[c], errors="coerce").astype("float64")
NAME = "windows" if PER_WINDOW else "features"
art_path = os.path.join(out, f"{NAME}.parquet")
art.to_parquet(art_path, index=False)

# %% Result
n_files = len(media_ids) - len(bad)
values = {"n_rows": len(media_ids), "n_files": n_files, "n_unreadable": len(bad), "n_out_rows": len(rows), "n_features": len(FEATURES),
          "sample_rate": SR, "frame_ms": 1000.0 * N_FFT / SR, "hop_ms": 1000.0 * HOP / SR}
for c in FEATURES:
    v = art[c].to_numpy(dtype=np.float64)
    v = v[np.isfinite(v)]
    if len(v):
        values[f"mean[{c}]"] = float(np.mean(v))
preview = [{k: (r[k] if not isinstance(r[k], float) or math.isfinite(r[k]) else None) for k in keys[: keys.index(FEATURES[0])] + FEATURES[:8]} for r in rows[:25]]
tables = [{"key": "features", "title": "Feature table (first rows and columns)",
           "columns": [{"key": k, "label": k, **({"type": "number"} if k in FEATURES or k in ("start_s", "end_s") else {})} for k in preview[0]],
           "rows": preview}]
if bad:
    tables.append({"key": "unreadable", "title": "Files that could not be read", "columns": [{"key": "file", "label": "File"}, {"key": "path", "label": "Path"}], "rows": bad[:50]})
charts = []
name, x = first
seg = x[: int(min(len(x), 10 * SR))]
M = dsp.power_to_db(dsp.mel_spectrogram(seg, SR, N_FFT, HOP, N_MELS), "max", 1e-10, 80.0)
mel_hz = dsp.mel_frequencies(N_MELS + 2, 0.0, SR / 2.0)[1:-1]
T = dsp.frame_times(M.shape[1], SR, HOP)
charts.append(cs.chart("spectrogram", "spectrogram", f"Mel spectrogram: {name}", {
    "x": cs.col("Time (s)", np.repeat(T, N_MELS), "numeric"),
    "y": cs.col("Frequency (Hz, mel band center)", np.tile(mel_hz, len(T)), "numeric"),
    "z": cs.col("Level (dB re max)", M.T.ravel(), "numeric"),
}, controls={"scale": "mel"}, note=f"Hann frames of {N_FFT} samples every {HOP} at {int(SR)} Hz, {N_MELS} Slaney mel bands, dB relative to the loudest cell (floor −80 dB)."))
pair = ("mfcc_1_mean", "mfcc_2_mean") if "mfcc_2_mean" in FEATURES else (("centroid_mean", "rms_mean") if "rms_mean" in FEATURES and "centroid_mean" in FEATURES else None)
if pair:
    roles = {"x": cs.col(pair[0], art[pair[0]].to_numpy(dtype=np.float64), "numeric"), "y": cs.col(pair[1], art[pair[1]].to_numpy(dtype=np.float64), "numeric")}
    if labels is not None:
        roles["color"] = cs.col(LABEL, art["label"].astype(str).tolist(), "categorical", [str(v) for v in df[LABEL].cat.categories][:8])
    charts.append(cs.chart("map", "scatter", "Files by their first two features" if not PER_WINDOW else "Windows by their first two features", roles, controls={"fit": "none"}))
assumptions = [
    {"key": "decoded", "label": "Files decode", "status": "warn" if bad else "pass",
     "detail": f"{len(bad)} of {len(media_ids)} listed files could not be read." if bad else "Every listed file was decoded."},
    {"key": "same_rate", "label": "One sample rate", "status": "info", "detail": f"Every file was resampled to {int(SR)} Hz and mixed to mono."},
    {"key": "summary_loses_order", "label": "Summaries lose order", "status": "info",
     "detail": "Each window is summarized on its own." if PER_WINDOW else "Each file is summarized as a whole; turn on windows to keep time."},
]
cs.publish({
    "title": "Audio features (MFCC, spectral shape, chroma, loudness)",
    "engine": cs.engine_info("numpy", "pandas", "scipy"),
    "n": n_files,
    "summary": f"{n_files} files described by {len(FEATURES)} features in {len(rows)} rows.",
    "statistics": [
        {"key": "n_files", "label": "Files read", "value": n_files},
        {"key": "n_out_rows", "label": "Rows in the table", "value": len(rows)},
        {"key": "n_features", "label": "Features", "value": len(FEATURES)},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": f"factors_{NAME}", "path": art_path, "format": "parquet"}],
})

Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.

Audio features frames every file at 32 ms with a 10 ms hop and turns each into 39 numbers: MFCC means and spreads, spectral shape, chroma and loudness. The settings travel with the result, so the table can be rebuilt. Save it as a dataset to cluster recordings or train a classifier on them.

07

Check: spectrograms

Checkpoint

Check yourself

With centered frames, the frame count is 1+⌊n/hop⌋1 + \lfloor n / \text{hop} \rfloor. How many frames does a 2-second clip at 16,000 samples a second get with a hop of 160 samples?

Show the answer

Answer: 201

n=32,000n = 32{,}000 samples, and 32,000/160=20032{,}000 / 160 = 200, plus one: 201 frames, one every 10 ms.

Check yourself

You need to time short clicks precisely. Which change helps most?

Show the answer

Answer: a

Short frames localize events in time; a small hop places frames densely. Longer frames trade time detail for frequency detail.

Check yourself

Why is a log spectrogram clamped at a floor before taking the log?

Show the answer

Answer: b

The log of zero is minus infinity. The floor is a real setting: change it and quiet passages look different to the model.

Check yourself

A vocoder trained on 80-band Slaney mels with a 1e-5 floor gets 80-band HTK mels with a 1e-10 floor. The shapes match. What do you expect?

Show the answer

Answer: b

Matching shapes hide mismatched conventions. The mel formula and the floor change the numbers, so the model reads them wrongly without any error.

08

Recap

Recap
  • A spectrogram is a stack of windowed FFT frames; frame length, hop and window define it.
  • Longer frames sharpen frequency and blur time.
  • Mel bands follow hearing; the log needs a floor; MFCCs summarize a log-mel frame.
  • The settings are part of the data: a model trained on one convention misreads another.

Concepts in this lesson