Skip to content

A first look at audio files

Profile a folder of recordings (length, loudness, clipping, silence), read waveforms and spectrograms, and turn each file into a row of features that other methods can use.

Applied ~14 min7 steps

What runs in CodeSplash

You will be able to

  • Read a collection profile and its flags (silent, clipped, mostly silent, quiet, loud)
  • Tell sample peak, RMS level and integrated loudness (LUFS) apart
  • Read a waveform and a spectrogram, and say what the frame length changes
  • Describe what MFCCs, spectral shape, chroma and the zero-crossing rate measure, and save them as a dataset
01

Recordings are long lists of numbers

Read

A sound file stores the air pressure at a microphone, measured thousands of times a second: the sample rateSample rateHow many samples per second a recording stores (16,000 for speech, 44,100 or 48,000 for music); it caps the highest frequency at half that.. Speech is often stored at 16,000 samples a second, music at 44,100 or 48,000. Each sample is a number between −1 and 1, where ±1 is the loudest the file can hold.

The app never copies your files. An audio folder added in Data links to them in place, and each run decodes every file once, at its own rate and with all its channels, so Python and R measure exactly the same samples.

02

A small test collection

In the app

The test folder holds seven short clips (tones, noise, a clipped chirp, a very quiet tone, silence and a speech-like sound), a text file named .wav and a path to a file that is gone.

Audio collection profile (duration, loudness, clipping, silence)Recorded · Python and R agreeRecorded 2026-11-25 · 27 values compared
R

7 audio files, 4.8 s in all; 1 silent, 1 clipped, 1 quiet.

Files read
7
Total duration (s)
4.800
Median loudness (LUFS)
−18.395
Clipped files
1

Assumptions

  • Files decode — 2 of 9 listed files could not be read.
  • Measured at each file's own rate — Sample rates: 8000 Hz (2 files), 16000 Hz (4 files), 22050 Hz (1 files).
  • Loudness needs 0.4 s — 1 files are silent or shorter than one 400 ms block, so they have no loudness.
  • Recordings of people — Voices can identify people; check consent before sharing files or results.

Flagged files

FileFlagDuration (s)Loudness (LUFS)Peak (dBFS)Clipped shareSilent share
chirp_loud.wavClipping0.8000−1.044−0.00030.53310
quiet.wavQuiet0.6000−54.284−50.48400
silence.wavSilent0.5000——01

Files (first 200)

FileDuration (s)Sample rate (Hz)ChannelsLoudness (LUFS)Flag
tone_a.wav0.800016,0001−14.903OK
tone_b.wav0.500022,0502−14.636OK
noise_a.wav0.600016,0001−26.342OK
chirp_loud.wav0.80008,0001−1.044Clipping
quiet.wav0.600016,0001−54.284Quiet
silence.wav0.50008,0001—Silent
speechlike.wav116,0001−21.888OK

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 collection profile (duration, loudness, clipping, silence)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.audio 1.0.0 · spec 1f5dd86ebe1c5a81
# 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")))
n_input <- nrow(df)
df[["path"]] <- factor(df[["path"]], levels = sort(unique(df[["path"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("path")]), , 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"))  # 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\":false,\"offset_seconds\":0,\"sample_rate\":null}}", simplifyVector = FALSE), "target/academy-parity/run-8142/describe.audio/folder_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
}

# %% Decode and measure each file (channels x samples at the analysis rate)
PATH <- "path"
LABEL <- NULL
CLIP_LEVEL <- 0.999; SILENCE_DB <- -60
CLIP_FLAG <- 0.001; SILENCE_FLAG <- 0.5; QUIET <- -40; LOUD <- -8
N_WAVES <- 4
status <- cs_media_status(media, media_ids)
paths <- as.character(df[[PATH]])
labels <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
files <- list(); clips <- list()
for (i in seq_along(media_ids)) {
  rec <- list(row = i - 1L, path = paths[i], file = basename(paths[i]), group = if (!is.null(labels)) labels[i] else NULL)
  x <- NULL
  rate <- NA_real_
  if (is.na(status[i])) {
    x <- tryCatch(cs_media_audio(media, media_ids[i])[[1]], cs_error = function(e) NULL)
    if (!is.null(x)) rate <- as.numeric(cs_media_audio_rates(media, media_ids[i])[1])  # each file at its own rate
  }
  if (is.null(x)) {
    rec$status <- "unreadable"
    files[[length(files) + 1]] <- rec
    next
  }
  s <- cs_audio_clip_stats(x, rate, CLIP_LEVEL, SILENCE_DB, 0.05, 0.025)
  rec <- c(rec, list(status = "ok", sample_rate = rate), s)
  rec$flag <- cs_audio_flag(s, CLIP_FLAG, SILENCE_FLAG, QUIET, LOUD)
  files[[length(files) + 1]] <- rec
  if (length(clips) < N_WAVES) clips[[length(clips) + 1]] <- list(rec = rec, x = x, rate = rate)  # kept only for the waveforms
}
ok <- Filter(function(r) r$status == "ok", files)
if (!length(ok)) cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an audio file that exists and can be decoded", count = length(files))
n_bad <- length(files) - length(ok)
if (n_bad) warnings <- c(warnings, sprintf("%d listed files could not be read and are left out.", n_bad))

# %% Artifact: one row per listed file
out <- cs_ml_out_dir("target/academy-parity/run-8142/describe.audio/folder_defaults/out-r")
fld <- function(field, na) lapply(files, function(r) if (is.null(r[[field]])) na else r[[field]])
art <- data.frame(
  row = vapply(files, function(r) as.integer(r$row), 0L), path = vapply(files, function(r) r$path, ""),
  file = vapply(files, function(r) r$file, ""), group = vapply(fld("group", NA_character_), as.character, ""),
  status = vapply(files, function(r) r$status, ""), sample_rate = vapply(fld("sample_rate", NA_real_), as.numeric, 0),
  duration_s = vapply(fld("duration_s", NA_real_), as.numeric, 0), channels = vapply(fld("channels", NA_integer_), as.integer, 0L),
  samples = vapply(fld("samples", NA_integer_), as.integer, 0L),
  loudness_lufs = vapply(fld("loudness_lufs", NA_real_), as.numeric, 0), peak_dbfs = vapply(fld("peak_dbfs", NA_real_), as.numeric, 0),
  rms_dbfs = vapply(fld("rms_dbfs", NA_real_), as.numeric, 0), crest_db = vapply(fld("crest_db", NA_real_), as.numeric, 0),
  clip_share = vapply(fld("clip_share", NA_real_), as.numeric, 0), silence_share = vapply(fld("silence_share", NA_real_), as.numeric, 0),
  dc_offset = vapply(fld("dc_offset", NA_real_), as.numeric, 0), flag = vapply(fld("flag", NA_character_), as.character, ""),
  stringsAsFactors = FALSE
)
nanoparquet::write_parquet(art, file.path(out, "audio_files.parquet"))

# %% Summary
fin <- function(v) !is.null(v) && is.finite(v)
D <- vapply(ok, function(r) r$duration_s, 0)
L <- unlist(lapply(ok, function(r) if (fin(r$loudness_lufs)) r$loudness_lufs else NULL))
flags <- vapply(ok, function(r) r$flag, "")
ch <- vapply(ok, function(r) r$channels, 0)
cshare <- unlist(lapply(ok, function(r) if (fin(r$clip_share)) r$clip_share else NULL))
sshare <- unlist(lapply(ok, function(r) if (fin(r$silence_share)) r$silence_share else NULL))
values <- list(
  n_rows = length(files), n_files = length(ok), n_unreadable = n_bad,
  total_duration_s = sum(D), duration_min = min(D), duration_median = stats::median(D), duration_max = max(D),
  n_mono = sum(ch == 1), n_stereo = sum(ch == 2), n_multichannel = sum(ch > 2),
  loudness_median = if (length(L)) stats::median(L) else NULL, loudness_min = if (length(L)) min(L) else NULL,
  loudness_max = if (length(L)) max(L) else NULL, n_no_loudness = length(ok) - length(L),
  peak_max_dbfs = max(vapply(ok, function(r) r$peak_dbfs, 0)),
  clip_share_mean = if (length(cshare)) mean(cshare) else NULL,
  silence_share_mean = if (length(sshare)) mean(sshare) else NULL,
  n_ok = sum(flags == "OK"), n_silent = sum(flags == "Silent"), n_clipping = sum(flags == "Clipping"),
  n_mostly_silent = sum(flags == "Mostly silent"), n_quiet = sum(flags == "Quiet"), n_loud = sum(flags == "Loud"),
  n_rates = length(unique(vapply(ok, function(r) r$sample_rate, 0)))
)
rates_ok <- vapply(ok, function(r) r$sample_rate, 0)
for (rate in sort(unique(rates_ok))) values[[sprintf("files_at_rate[%d]", as.integer(rate))]] <- sum(rates_ok == rate)
group_rows <- list()
if (!is.null(LABEL)) {
  for (g in levels(df[[LABEL]])) {
    rs <- Filter(function(r) identical(r$group, g), ok)
    if (!length(rs)) next
    lg <- unlist(lapply(rs, function(r) if (fin(r$loudness_lufs)) r$loudness_lufs else NULL))
    values[[sprintf("files[%s]", g)]] <- length(rs)
    values[[sprintf("duration_median[%s]", g)]] <- stats::median(vapply(rs, function(r) r$duration_s, 0))
    if (length(lg)) values[[sprintf("loudness_median[%s]", g)]] <- stats::median(lg)
    group_rows[[length(group_rows) + 1]] <- list(group = g, files = length(rs), duration_median = values[[sprintf("duration_median[%s]", g)]],
                                                 loudness_median = values[[sprintf("loudness_median[%s]", g)]],
                                                 flagged = sum(vapply(rs, function(r) r$flag != "OK", TRUE)))
  }
}

# %% Result
FLAG_LEVELS <- c("OK", "Silent", "Clipping", "Mostly silent", "Quiet", "Loud", "Empty")
fl <- Filter(function(r) r$flag != "OK", ok)
fl <- fl[seq_len(min(50, length(fl)))]
nf <- function(v) if (is.numeric(v) && !is.finite(v)) NULL else v
tables <- list(list(
  key = "flagged", title = "Flagged files",
  columns = list(list(key = "file", label = "File"), list(key = "flag", label = "Flag"), list(key = "duration_s", label = "Duration (s)", type = "number"),
                 list(key = "loudness_lufs", label = "Loudness (LUFS)", type = "number"), list(key = "peak_dbfs", label = "Peak (dBFS)", type = "number"),
                 list(key = "clip_share", label = "Clipped share", type = "number"), list(key = "silence_share", label = "Silent share", type = "number")),
  rows = lapply(fl, function(r) list(file = r$file, flag = r$flag, duration_s = nf(r$duration_s), loudness_lufs = nf(r$loudness_lufs),
                                     peak_dbfs = nf(r$peak_dbfs), clip_share = nf(r$clip_share), silence_share = nf(r$silence_share)))
))
if (length(group_rows)) {
  tables[[length(tables) + 1]] <- list(key = "groups", title = paste0("By ", LABEL), columns = list(
    list(key = "group", label = LABEL), list(key = "files", label = "Files", type = "integer"), list(key = "duration_median", label = "Median duration (s)", type = "number"),
    list(key = "loudness_median", label = "Median loudness (LUFS)", type = "number"), list(key = "flagged", label = "Flagged", type = "integer")), rows = group_rows)
}
tables[[length(tables) + 1]] <- list(key = "files", title = "Files (first 200)", columns = list(
  list(key = "file", label = "File"), list(key = "duration_s", label = "Duration (s)", type = "number"), list(key = "sample_rate", label = "Sample rate (Hz)", type = "integer"),
  list(key = "channels", label = "Channels", type = "integer"), list(key = "loudness_lufs", label = "Loudness (LUFS)", type = "number"), list(key = "flag", label = "Flag")),
  rows = lapply(ok[seq_len(min(200, length(ok)))], function(r) list(file = r$file, media_id = media_ids[r$row + 1], duration_s = r$duration_s, sample_rate = as.integer(r$sample_rate),
                                                                   channels = r$channels, loudness_lufs = nf(r$loudness_lufs), flag = r$flag)))
bad <- Filter(function(r) r$status != "ok", files)
if (length(bad)) {
  bad <- bad[seq_len(min(50, length(bad)))]
  tables[[length(tables) + 1]] <- list(key = "unreadable", title = "Files that could not be read", columns = list(list(key = "file", label = "File"), list(key = "path", label = "Path")),
                                       rows = lapply(bad, function(r) list(file = r$file, path = r$path)))
}
charts <- list()
if (length(L)) charts[[length(charts) + 1]] <- cs_chart("loudness", "histogram", "Integrated loudness", list(x = cs_col("Loudness (LUFS)", L, "numeric")), controls = list(scale = "count", kde = FALSE))
withl <- Filter(function(r) fin(r$loudness_lufs), ok)
if (length(withl)) {
  charts[[length(charts) + 1]] <- cs_chart("levels", "scatter", "Loudness by duration", list(
    x = cs_col("Duration (s)", vapply(withl, function(r) r$duration_s, 0), "numeric"),
    y = cs_col("Loudness (LUFS)", vapply(withl, function(r) r$loudness_lufs, 0), "numeric"),
    color = cs_col("Flag", vapply(withl, function(r) r$flag, ""), "categorical", FLAG_LEVELS)
  ), controls = list(fit = "none"))
}
if (N_WAVES > 0 && length(clips)) {
  t0 <- numeric(0); t1 <- numeric(0); lo <- numeric(0); hi <- numeric(0); rm <- numeric(0); trk <- character(0)
  for (cl in clips) {
    e <- cs_audio_envelope(cl$x, cl$rate, 600)
    t0 <- c(t0, e$start); t1 <- c(t1, e$end); lo <- c(lo, e$min); hi <- c(hi, e$max); rm <- c(rm, e$rms); trk <- c(trk, rep(cl$rec$file, length(e$min)))
  }
  charts[[length(charts) + 1]] <- cs_chart("waveforms", "waveform", "Waveforms", list(
    time = cs_col("Time (s)", t0, "numeric"), end = cs_col("End (s)", t1, "numeric"),
    min = cs_col("Min", lo, "numeric"), max = cs_col("Max", hi, "numeric"), rms = cs_col("RMS", rm, "numeric"),
    track = cs_col("File", trk, "categorical", unique(trk))
  ), controls = list(clip = CLIP_LEVEL))
}
assumptions <- list(
  list(key = "decoded", label = "Files decode", status = if (n_bad) "warn" else "pass",
       detail = if (n_bad) sprintf("%d of %d listed files could not be read.", n_bad, length(files)) else "Every listed file was decoded."),
  list(key = "native_rate", label = "Measured at each file's own rate", status = "info",
       detail = paste0("Sample rates: ", paste(vapply(sort(unique(rates_ok)), function(k) sprintf("%d Hz (%d files)", as.integer(k), sum(rates_ok == k)), ""), collapse = ", "), ".")),
  list(key = "short_files", label = "Loudness needs 0.4 s", status = if (values$n_no_loudness) "warn" else "pass",
       detail = if (values$n_no_loudness) sprintf("%d files are silent or shorter than one 400 ms block, so they have no loudness.", values$n_no_loudness) else "Every file has a loudness."),
  list(key = "personal_data", label = "Recordings of people", status = "info", detail = "Voices can identify people; check consent before sharing files or results.")
)
cs_publish(list(
  title = "Audio collection profile (duration, loudness, clipping, silence)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(ok),
  summary = sprintf("%d audio files, %.1f s in all; %d silent, %d clipped, %d quiet.", length(ok), values$total_duration_s, values$n_silent, values$n_clipping, values$n_quiet),
  statistics = list(
    list(key = "n_files", label = "Files read", value = length(ok)),
    list(key = "total_duration_s", label = "Total duration (s)", value = values$total_duration_s),
    list(key = "loudness_median", label = "Median loudness (LUFS)", value = values$loudness_median),
    list(key = "n_clipping", label = "Clipped files", value = values$n_clipping)
  ),
  tables = tables,
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "audio_files", path = file.path(out, "audio_files.parquet"), format = "parquet"))
))
Python

7 audio files, 4.8 s in all; 1 silent, 1 clipped, 1 quiet.

Files read
7
Total duration (s)
4.800
Median loudness (LUFS)
−18.395
Clipped files
1

Assumptions

  • Files decode — 2 of 9 listed files could not be read.
  • Measured at each file's own rate — Sample rates: 8000 Hz (2 files), 16000 Hz (4 files), 22050 Hz (1 files).
  • Loudness needs 0.4 s — 1 files are silent or shorter than one 400 ms block, so they have no loudness.
  • Recordings of people — Voices can identify people; check consent before sharing files or results.

Flagged files

FileFlagDuration (s)Loudness (LUFS)Peak (dBFS)Clipped shareSilent share
chirp_loud.wavClipping0.8000−1.044−0.00030.53310
quiet.wavQuiet0.6000−54.284−50.48400
silence.wavSilent0.5000——01

Files (first 200)

FileDuration (s)Sample rate (Hz)ChannelsLoudness (LUFS)Flag
tone_a.wav0.800016,0001−14.903OK
tone_b.wav0.500022,0502−14.636OK
noise_a.wav0.600016,0001−26.342OK
chirp_loud.wav0.80008,0001−1.044Clipping
quiet.wav0.600016,0001−54.284Quiet
silence.wav0.50008,0001—Silent
speechlike.wav116,0001−21.888OK

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 collection profile (duration, loudness, clipping, silence)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.audio 1.0.0 · spec 1f5dd86ebe1c5a81
# 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 describe as ad
from codesplash.errors import CsError

# %% Data
df = pd.read_parquet("tests/parity/fixtures/aud1_clips.parquet", columns=["path"])
n_input = len(df)
df["path"] = pd.Categorical(df["path"], categories=sorted(df["path"].dropna().unique()))
df = df.dropna(subset=["path"])  # listwise deletion over the analysis columns
df["path"] = df["path"].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"])  # 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\":false,\"offset_seconds\":0,\"sample_rate\":null}}"), "target/academy-parity/run-8142/describe.audio/folder_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

# %% Decode and measure each file (channels × samples at the analysis rate)
PATH = "path"
LABEL = None
CLIP_LEVEL, SILENCE_DB = 0.999, -60
CLIP_FLAG, SILENCE_FLAG, QUIET, LOUD = 0.001, 0.5, -40, -8
N_WAVES = 4
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
files, clips = [], []
for i, mid in enumerate(media_ids):
    rec = {"row": i, "path": paths[i], "file": os.path.basename(paths[i]), "group": labels[i] if labels else None}
    x = None
    if status[i] is None:
        try:
            x = cs_media.audio(media, [mid])[0]
            rate = float(cs_media.audio_rates(media, [mid])[0])  # each file at its own rate
        except CsError:
            x = None
    if x is None:
        rec["status"] = "unreadable"
        files.append(rec)
        continue
    s = ad.clip_stats(x, rate, CLIP_LEVEL, SILENCE_DB, 0.05, 0.025)
    rec.update(status="ok", sample_rate=rate, **s)
    rec["flag"] = ad.flag(s, CLIP_FLAG, SILENCE_FLAG, QUIET, LOUD)
    files.append(rec)
    if len(clips) < N_WAVES:
        clips.append((rec, x, rate))  # kept only for the waveforms
ok = [r for r in files if r["status"] == "ok"]
if not ok:
    cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an audio file that exists and can be decoded", count=len(files))
warnings = list(warnings)
n_bad = len(files) - len(ok)
if n_bad:
    warnings.append(f"{n_bad} listed files could not be read and are left out.")

# %% Artifact: one row per listed file
out = csml.out_dir("target/academy-parity/run-8142/describe.audio/folder_defaults/out-python")
COLS = ["row", "path", "file", "group", "status", "sample_rate", "duration_s", "channels", "samples", "loudness_lufs", "peak_dbfs", "rms_dbfs", "crest_db",
        "clip_share", "silence_share", "dc_offset", "flag"]
art = pd.DataFrame([{c: r.get(c) for c in COLS} for r in files], columns=COLS)
for c in ("path", "file", "group", "status", "flag"):
    art[c] = art[c].astype("string")
for c in ("sample_rate", "duration_s", "loudness_lufs", "peak_dbfs", "rms_dbfs", "crest_db", "clip_share", "silence_share", "dc_offset"):
    art[c] = pd.to_numeric(art[c], errors="coerce").astype("float64")
for c in ("channels", "samples"):
    art[c] = pd.array([None if pd.isna(v) else int(v) for v in art[c]], dtype="Int64")
art.to_parquet(os.path.join(out, "audio_files.parquet"), index=False)

# %% Summary
def fin(v):
    return v is not None and math.isfinite(v)


D = np.array([r["duration_s"] for r in ok])
L = np.array([r["loudness_lufs"] for r in ok if fin(r["loudness_lufs"])])
flags = [r["flag"] for r in ok]
values = {
    "n_rows": len(files), "n_files": len(ok), "n_unreadable": n_bad,
    "total_duration_s": float(np.sum(D)), "duration_min": float(np.min(D)), "duration_median": float(np.median(D)), "duration_max": float(np.max(D)),
    "n_mono": sum(r["channels"] == 1 for r in ok), "n_stereo": sum(r["channels"] == 2 for r in ok), "n_multichannel": sum(r["channels"] > 2 for r in ok),
    "loudness_median": float(np.median(L)) if len(L) else None, "loudness_min": float(np.min(L)) if len(L) else None,
    "loudness_max": float(np.max(L)) if len(L) else None, "n_no_loudness": len(ok) - len(L),
    "peak_max_dbfs": float(max(r["peak_dbfs"] for r in ok)),
    "clip_share_mean": float(np.mean([r["clip_share"] for r in ok if fin(r["clip_share"])])) if any(fin(r["clip_share"]) for r in ok) else None,
    "silence_share_mean": float(np.mean([r["silence_share"] for r in ok if fin(r["silence_share"])])) if any(fin(r["silence_share"]) for r in ok) else None,
    "n_ok": flags.count("OK"), "n_silent": flags.count("Silent"), "n_clipping": flags.count("Clipping"),
    "n_mostly_silent": flags.count("Mostly silent"), "n_quiet": flags.count("Quiet"), "n_loud": flags.count("Loud"),
    "n_rates": len({r["sample_rate"] for r in ok}),
}
for rate in sorted({r["sample_rate"] for r in ok}):
    values[f"files_at_rate[{int(rate)}]"] = sum(r["sample_rate"] == rate for r in ok)
group_rows = []
if LABEL is not None:
    for g in [str(v) for v in df[LABEL].cat.categories]:
        rs = [r for r in ok if r["group"] == g]
        if not rs:
            continue
        lg = [r["loudness_lufs"] for r in rs if fin(r["loudness_lufs"])]
        values[f"files[{g}]"] = len(rs)
        values[f"duration_median[{g}]"] = float(np.median([r["duration_s"] for r in rs]))
        if lg:
            values[f"loudness_median[{g}]"] = float(np.median(lg))
        group_rows.append({"group": g, "files": len(rs), "duration_median": values[f"duration_median[{g}]"],
                           "loudness_median": values.get(f"loudness_median[{g}]"), "flagged": sum(r["flag"] != "OK" for r in rs)})

# %% Result
FLAG_LEVELS = ["OK", "Silent", "Clipping", "Mostly silent", "Quiet", "Loud", "Empty"]
flagged = [r for r in ok if r["flag"] != "OK"][:50]
tables = [{
    "key": "flagged", "title": "Flagged files",
    "columns": [{"key": "file", "label": "File"}, {"key": "flag", "label": "Flag"}, {"key": "duration_s", "label": "Duration (s)", "type": "number"},
                {"key": "loudness_lufs", "label": "Loudness (LUFS)", "type": "number"}, {"key": "peak_dbfs", "label": "Peak (dBFS)", "type": "number"},
                {"key": "clip_share", "label": "Clipped share", "type": "number"}, {"key": "silence_share", "label": "Silent share", "type": "number"}],
    "rows": [{k: (r[k] if not isinstance(r[k], float) or math.isfinite(r[k]) else None) for k in ("file", "flag", "duration_s", "loudness_lufs", "peak_dbfs", "clip_share", "silence_share")} for r in flagged],
}]
if group_rows:
    tables.append({"key": "groups", "title": f"By {LABEL}", "columns": [
        {"key": "group", "label": LABEL}, {"key": "files", "label": "Files", "type": "integer"}, {"key": "duration_median", "label": "Median duration (s)", "type": "number"},
        {"key": "loudness_median", "label": "Median loudness (LUFS)", "type": "number"}, {"key": "flagged", "label": "Flagged", "type": "integer"}], "rows": group_rows})
tables.append({"key": "files", "title": "Files (first 200)", "columns": [
    {"key": "file", "label": "File"}, {"key": "duration_s", "label": "Duration (s)", "type": "number"}, {"key": "sample_rate", "label": "Sample rate (Hz)", "type": "integer"},
    {"key": "channels", "label": "Channels", "type": "integer"}, {"key": "loudness_lufs", "label": "Loudness (LUFS)", "type": "number"}, {"key": "flag", "label": "Flag"}],
    "rows": [{"file": r["file"], "media_id": media_ids[r["row"]], "duration_s": r["duration_s"], "sample_rate": int(r["sample_rate"]), "channels": r["channels"],
              "loudness_lufs": r["loudness_lufs"] if math.isfinite(r["loudness_lufs"]) else None, "flag": r["flag"]} for r in ok[:200]]})
bad = [r for r in files if r["status"] != "ok"][:50]
if bad:
    tables.append({"key": "unreadable", "title": "Files that could not be read", "columns": [{"key": "file", "label": "File"}, {"key": "path", "label": "Path"}],
                   "rows": [{"file": r["file"], "path": r["path"]} for r in bad]})
charts = []
if len(L):
    charts.append(cs.chart("loudness", "histogram", "Integrated loudness", {"x": cs.col("Loudness (LUFS)", L, "numeric")}, controls={"scale": "count", "kde": False}))
withl = [r for r in ok if fin(r["loudness_lufs"])]
if withl:
    charts.append(cs.chart("levels", "scatter", "Loudness by duration", {
        "x": cs.col("Duration (s)", [r["duration_s"] for r in withl], "numeric"),
        "y": cs.col("Loudness (LUFS)", [r["loudness_lufs"] for r in withl], "numeric"),
        "color": cs.col("Flag", [r["flag"] for r in withl], "categorical", FLAG_LEVELS),
    }, controls={"fit": "none"}))
if N_WAVES > 0:
    t0, t1, lo, hi, rm, trk = [], [], [], [], [], []
    for rec, x, rate in clips:
        e = ad.envelope(x, rate, 600)
        t0 += e["start"]; t1 += e["end"]; lo += e["min"]; hi += e["max"]; rm += e["rms"]; trk += [rec["file"]] * len(e["min"])
    if t0:
        charts.append(cs.chart("waveforms", "waveform", "Waveforms", {
            "time": cs.col("Time (s)", t0, "numeric"), "end": cs.col("End (s)", t1, "numeric"),
            "min": cs.col("Min", lo, "numeric"), "max": cs.col("Max", hi, "numeric"), "rms": cs.col("RMS", rm, "numeric"),
            "track": cs.col("File", trk, "categorical", list(dict.fromkeys(trk))),
        }, controls={"clip": CLIP_LEVEL}))
assumptions = [
    {"key": "decoded", "label": "Files decode", "status": "warn" if n_bad else "pass",
     "detail": f"{n_bad} of {len(files)} listed files could not be read." if n_bad else "Every listed file was decoded."},
    {"key": "native_rate", "label": "Measured at each file's own rate", "status": "info",
     "detail": "Sample rates: " + ", ".join(f"{int(k)} Hz ({v} files)" for k, v in sorted({r['sample_rate']: sum(q['sample_rate'] == r['sample_rate'] for q in ok) for r in ok}.items())) + "."},
    {"key": "short_files", "label": "Loudness needs 0.4 s", "status": "warn" if values["n_no_loudness"] else "pass",
     "detail": f"{values['n_no_loudness']} files are silent or shorter than one 400 ms block, so they have no loudness." if values["n_no_loudness"] else "Every file has a loudness."},
    {"key": "personal_data", "label": "Recordings of people", "status": "info", "detail": "Voices can identify people; check consent before sharing files or results."},
]
cs.publish({
    "title": "Audio collection profile (duration, loudness, clipping, silence)",
    "engine": cs.engine_info("numpy", "pandas", "scipy"),
    "n": len(ok),
    "summary": f"{len(ok)} audio files, {values['total_duration_s']:.1f} s in all; {values['n_silent']} silent, {values['n_clipping']} clipped, {values['n_quiet']} quiet.",
    "statistics": [
        {"key": "n_files", "label": "Files read", "value": len(ok)},
        {"key": "total_duration_s", "label": "Total duration (s)", "value": values["total_duration_s"]},
        {"key": "loudness_median", "label": "Median loudness (LUFS)", "value": values["loudness_median"]},
        {"key": "n_clipping", "label": "Clipped files", "value": values["n_clipping"]},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "audio_files", "path": os.path.join(out, "audio_files.parquet"), "format": "parquet"}],
})

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

The profile read 7 of 9 listed files, 4.80 seconds in all. The two it couldn't read are listed in their own table, not silently dropped.

03

Three kinds of loud

Checkpoint
  • The sample peak is the largest sample, in dBFSdBFS (decibels relative to full scale)A level in decibels below the loudest value a file can hold: 0 dBFS is full scale, −6 dBFS is half the amplitude.: 0 dBFS is full scale.
  • The RMS level is the average strength: the square root of the mean squared sample.
  • Integrated loudnessIntegrated loudness (LUFS)How loud a whole recording sounds, in LUFS: K-weighted levels of 400 ms blocks, gated to ignore silence (ITU-R BS.1770). (LUFS) is how loud the whole file sounds: the signal is filtered the way ears weigh frequencies, cut into 400 ms blocks, and quiet blocks are ignored (ITU-R BS.1770).

The loudest file here reads −1.04 LUFS and the quietest −54.3 LUFS. Streaming services aim near −14 LUFS.

Check yourself

Two files both peak at −1 dBFS. One is a single drum hit in silence, the other a compressed pop song. Which has the higher integrated loudness?

Show the answer

Answer: b

Peaks say how close a file comes to full scale; loudness says how strong it is over time. A short hit in silence has a high peak and low loudness, and BS.1770 also gates the silent blocks out.

04

Flags

Explore

Each file gets one flag, first match wins: Silent, Clipping, Mostly silent, Quiet, Loud, else OK. With the defaults, 1 file is clipped and 1 is silent.

ClippingClippingSamples stuck at full scale because the signal was louder than the recording could hold; it sounds harsh and can't be undone. means the signal was louder than the recording could hold, so the samples sit flat at full scale. The silence shareSilence shareThe share of 50 ms frames whose RMS level is below the silence threshold (−60 dBFS by default). is the share of 50 ms frames below −60 dBFS.

Audio collection profile (duration, loudness, clipping, silence)Recorded · Python and R agreeRecorded 2026-11-25 · 41 values compared
R

7 audio files, 4.8 s in all; 2 silent, 1 clipped, 0 quiet.

Files read
7
Total duration (s)
4.800
Median loudness (LUFS)
−18.395
Clipped files
1

Assumptions

  • Files decode — 2 of 9 listed files could not be read.
  • Measured at each file's own rate — Sample rates: 8000 Hz (2 files), 16000 Hz (4 files), 22050 Hz (1 files).
  • Loudness needs 0.4 s — 1 files are silent or shorter than one 400 ms block, so they have no loudness.
  • Recordings of people — Voices can identify people; check consent before sharing files or results.

Flagged files

FileFlagDuration (s)Loudness (LUFS)Peak (dBFS)Clipped shareSilent share
chirp_loud.wavClipping0.8000−1.044−0.00030.53890
quiet.wavSilent0.6000−54.284−50.48401
silence.wavSilent0.5000——01
speechlike.wavMostly silent1−21.888−7.93000.6154

By label

labelFilesMedian duration (s)Median loudness (LUFS)Flagged
chirp10.8000−1.0441
noise10.6000−26.3420
silence10.5000—1
speech11−21.8881
tone30.6000−14.9031

Files (first 200)

FileDuration (s)Sample rate (Hz)ChannelsLoudness (LUFS)Flag
tone_a.wav0.800016,0001−14.903OK
tone_b.wav0.500022,0502−14.636OK
noise_a.wav0.600016,0001−26.342OK
chirp_loud.wav0.80008,0001−1.044Clipping
quiet.wav0.600016,0001−54.284Silent
silence.wav0.50008,0001—Silent
speechlike.wav116,0001−21.888Mostly silent

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 collection profile (duration, loudness, clipping, silence)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.audio 1.0.0 · spec d5d5727965bc91d8
# 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\":false,\"offset_seconds\":0,\"sample_rate\":null}}", simplifyVector = FALSE), "target/academy-parity/run-8142/describe.audio/grouped_strict/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
}

# %% Decode and measure each file (channels x samples at the analysis rate)
PATH <- "path"
LABEL <- "label"
CLIP_LEVEL <- 0.99; SILENCE_DB <- -50
CLIP_FLAG <- 0.0; SILENCE_FLAG <- 0.3; QUIET <- -30; LOUD <- -12
N_WAVES <- 2
status <- cs_media_status(media, media_ids)
paths <- as.character(df[[PATH]])
labels <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
files <- list(); clips <- list()
for (i in seq_along(media_ids)) {
  rec <- list(row = i - 1L, path = paths[i], file = basename(paths[i]), group = if (!is.null(labels)) labels[i] else NULL)
  x <- NULL
  rate <- NA_real_
  if (is.na(status[i])) {
    x <- tryCatch(cs_media_audio(media, media_ids[i])[[1]], cs_error = function(e) NULL)
    if (!is.null(x)) rate <- as.numeric(cs_media_audio_rates(media, media_ids[i])[1])  # each file at its own rate
  }
  if (is.null(x)) {
    rec$status <- "unreadable"
    files[[length(files) + 1]] <- rec
    next
  }
  s <- cs_audio_clip_stats(x, rate, CLIP_LEVEL, SILENCE_DB, 0.05, 0.025)
  rec <- c(rec, list(status = "ok", sample_rate = rate), s)
  rec$flag <- cs_audio_flag(s, CLIP_FLAG, SILENCE_FLAG, QUIET, LOUD)
  files[[length(files) + 1]] <- rec
  if (length(clips) < N_WAVES) clips[[length(clips) + 1]] <- list(rec = rec, x = x, rate = rate)  # kept only for the waveforms
}
ok <- Filter(function(r) r$status == "ok", files)
if (!length(ok)) cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an audio file that exists and can be decoded", count = length(files))
n_bad <- length(files) - length(ok)
if (n_bad) warnings <- c(warnings, sprintf("%d listed files could not be read and are left out.", n_bad))

# %% Artifact: one row per listed file
out <- cs_ml_out_dir("target/academy-parity/run-8142/describe.audio/grouped_strict/out-r")
fld <- function(field, na) lapply(files, function(r) if (is.null(r[[field]])) na else r[[field]])
art <- data.frame(
  row = vapply(files, function(r) as.integer(r$row), 0L), path = vapply(files, function(r) r$path, ""),
  file = vapply(files, function(r) r$file, ""), group = vapply(fld("group", NA_character_), as.character, ""),
  status = vapply(files, function(r) r$status, ""), sample_rate = vapply(fld("sample_rate", NA_real_), as.numeric, 0),
  duration_s = vapply(fld("duration_s", NA_real_), as.numeric, 0), channels = vapply(fld("channels", NA_integer_), as.integer, 0L),
  samples = vapply(fld("samples", NA_integer_), as.integer, 0L),
  loudness_lufs = vapply(fld("loudness_lufs", NA_real_), as.numeric, 0), peak_dbfs = vapply(fld("peak_dbfs", NA_real_), as.numeric, 0),
  rms_dbfs = vapply(fld("rms_dbfs", NA_real_), as.numeric, 0), crest_db = vapply(fld("crest_db", NA_real_), as.numeric, 0),
  clip_share = vapply(fld("clip_share", NA_real_), as.numeric, 0), silence_share = vapply(fld("silence_share", NA_real_), as.numeric, 0),
  dc_offset = vapply(fld("dc_offset", NA_real_), as.numeric, 0), flag = vapply(fld("flag", NA_character_), as.character, ""),
  stringsAsFactors = FALSE
)
nanoparquet::write_parquet(art, file.path(out, "audio_files.parquet"))

# %% Summary
fin <- function(v) !is.null(v) && is.finite(v)
D <- vapply(ok, function(r) r$duration_s, 0)
L <- unlist(lapply(ok, function(r) if (fin(r$loudness_lufs)) r$loudness_lufs else NULL))
flags <- vapply(ok, function(r) r$flag, "")
ch <- vapply(ok, function(r) r$channels, 0)
cshare <- unlist(lapply(ok, function(r) if (fin(r$clip_share)) r$clip_share else NULL))
sshare <- unlist(lapply(ok, function(r) if (fin(r$silence_share)) r$silence_share else NULL))
values <- list(
  n_rows = length(files), n_files = length(ok), n_unreadable = n_bad,
  total_duration_s = sum(D), duration_min = min(D), duration_median = stats::median(D), duration_max = max(D),
  n_mono = sum(ch == 1), n_stereo = sum(ch == 2), n_multichannel = sum(ch > 2),
  loudness_median = if (length(L)) stats::median(L) else NULL, loudness_min = if (length(L)) min(L) else NULL,
  loudness_max = if (length(L)) max(L) else NULL, n_no_loudness = length(ok) - length(L),
  peak_max_dbfs = max(vapply(ok, function(r) r$peak_dbfs, 0)),
  clip_share_mean = if (length(cshare)) mean(cshare) else NULL,
  silence_share_mean = if (length(sshare)) mean(sshare) else NULL,
  n_ok = sum(flags == "OK"), n_silent = sum(flags == "Silent"), n_clipping = sum(flags == "Clipping"),
  n_mostly_silent = sum(flags == "Mostly silent"), n_quiet = sum(flags == "Quiet"), n_loud = sum(flags == "Loud"),
  n_rates = length(unique(vapply(ok, function(r) r$sample_rate, 0)))
)
rates_ok <- vapply(ok, function(r) r$sample_rate, 0)
for (rate in sort(unique(rates_ok))) values[[sprintf("files_at_rate[%d]", as.integer(rate))]] <- sum(rates_ok == rate)
group_rows <- list()
if (!is.null(LABEL)) {
  for (g in levels(df[[LABEL]])) {
    rs <- Filter(function(r) identical(r$group, g), ok)
    if (!length(rs)) next
    lg <- unlist(lapply(rs, function(r) if (fin(r$loudness_lufs)) r$loudness_lufs else NULL))
    values[[sprintf("files[%s]", g)]] <- length(rs)
    values[[sprintf("duration_median[%s]", g)]] <- stats::median(vapply(rs, function(r) r$duration_s, 0))
    if (length(lg)) values[[sprintf("loudness_median[%s]", g)]] <- stats::median(lg)
    group_rows[[length(group_rows) + 1]] <- list(group = g, files = length(rs), duration_median = values[[sprintf("duration_median[%s]", g)]],
                                                 loudness_median = values[[sprintf("loudness_median[%s]", g)]],
                                                 flagged = sum(vapply(rs, function(r) r$flag != "OK", TRUE)))
  }
}

# %% Result
FLAG_LEVELS <- c("OK", "Silent", "Clipping", "Mostly silent", "Quiet", "Loud", "Empty")
fl <- Filter(function(r) r$flag != "OK", ok)
fl <- fl[seq_len(min(50, length(fl)))]
nf <- function(v) if (is.numeric(v) && !is.finite(v)) NULL else v
tables <- list(list(
  key = "flagged", title = "Flagged files",
  columns = list(list(key = "file", label = "File"), list(key = "flag", label = "Flag"), list(key = "duration_s", label = "Duration (s)", type = "number"),
                 list(key = "loudness_lufs", label = "Loudness (LUFS)", type = "number"), list(key = "peak_dbfs", label = "Peak (dBFS)", type = "number"),
                 list(key = "clip_share", label = "Clipped share", type = "number"), list(key = "silence_share", label = "Silent share", type = "number")),
  rows = lapply(fl, function(r) list(file = r$file, flag = r$flag, duration_s = nf(r$duration_s), loudness_lufs = nf(r$loudness_lufs),
                                     peak_dbfs = nf(r$peak_dbfs), clip_share = nf(r$clip_share), silence_share = nf(r$silence_share)))
))
if (length(group_rows)) {
  tables[[length(tables) + 1]] <- list(key = "groups", title = paste0("By ", LABEL), columns = list(
    list(key = "group", label = LABEL), list(key = "files", label = "Files", type = "integer"), list(key = "duration_median", label = "Median duration (s)", type = "number"),
    list(key = "loudness_median", label = "Median loudness (LUFS)", type = "number"), list(key = "flagged", label = "Flagged", type = "integer")), rows = group_rows)
}
tables[[length(tables) + 1]] <- list(key = "files", title = "Files (first 200)", columns = list(
  list(key = "file", label = "File"), list(key = "duration_s", label = "Duration (s)", type = "number"), list(key = "sample_rate", label = "Sample rate (Hz)", type = "integer"),
  list(key = "channels", label = "Channels", type = "integer"), list(key = "loudness_lufs", label = "Loudness (LUFS)", type = "number"), list(key = "flag", label = "Flag")),
  rows = lapply(ok[seq_len(min(200, length(ok)))], function(r) list(file = r$file, media_id = media_ids[r$row + 1], duration_s = r$duration_s, sample_rate = as.integer(r$sample_rate),
                                                                   channels = r$channels, loudness_lufs = nf(r$loudness_lufs), flag = r$flag)))
bad <- Filter(function(r) r$status != "ok", files)
if (length(bad)) {
  bad <- bad[seq_len(min(50, length(bad)))]
  tables[[length(tables) + 1]] <- list(key = "unreadable", title = "Files that could not be read", columns = list(list(key = "file", label = "File"), list(key = "path", label = "Path")),
                                       rows = lapply(bad, function(r) list(file = r$file, path = r$path)))
}
charts <- list()
if (length(L)) charts[[length(charts) + 1]] <- cs_chart("loudness", "histogram", "Integrated loudness", list(x = cs_col("Loudness (LUFS)", L, "numeric")), controls = list(scale = "count", kde = FALSE))
withl <- Filter(function(r) fin(r$loudness_lufs), ok)
if (length(withl)) {
  charts[[length(charts) + 1]] <- cs_chart("levels", "scatter", "Loudness by duration", list(
    x = cs_col("Duration (s)", vapply(withl, function(r) r$duration_s, 0), "numeric"),
    y = cs_col("Loudness (LUFS)", vapply(withl, function(r) r$loudness_lufs, 0), "numeric"),
    color = cs_col("Flag", vapply(withl, function(r) r$flag, ""), "categorical", FLAG_LEVELS)
  ), controls = list(fit = "none"))
}
if (N_WAVES > 0 && length(clips)) {
  t0 <- numeric(0); t1 <- numeric(0); lo <- numeric(0); hi <- numeric(0); rm <- numeric(0); trk <- character(0)
  for (cl in clips) {
    e <- cs_audio_envelope(cl$x, cl$rate, 600)
    t0 <- c(t0, e$start); t1 <- c(t1, e$end); lo <- c(lo, e$min); hi <- c(hi, e$max); rm <- c(rm, e$rms); trk <- c(trk, rep(cl$rec$file, length(e$min)))
  }
  charts[[length(charts) + 1]] <- cs_chart("waveforms", "waveform", "Waveforms", list(
    time = cs_col("Time (s)", t0, "numeric"), end = cs_col("End (s)", t1, "numeric"),
    min = cs_col("Min", lo, "numeric"), max = cs_col("Max", hi, "numeric"), rms = cs_col("RMS", rm, "numeric"),
    track = cs_col("File", trk, "categorical", unique(trk))
  ), controls = list(clip = CLIP_LEVEL))
}
assumptions <- list(
  list(key = "decoded", label = "Files decode", status = if (n_bad) "warn" else "pass",
       detail = if (n_bad) sprintf("%d of %d listed files could not be read.", n_bad, length(files)) else "Every listed file was decoded."),
  list(key = "native_rate", label = "Measured at each file's own rate", status = "info",
       detail = paste0("Sample rates: ", paste(vapply(sort(unique(rates_ok)), function(k) sprintf("%d Hz (%d files)", as.integer(k), sum(rates_ok == k)), ""), collapse = ", "), ".")),
  list(key = "short_files", label = "Loudness needs 0.4 s", status = if (values$n_no_loudness) "warn" else "pass",
       detail = if (values$n_no_loudness) sprintf("%d files are silent or shorter than one 400 ms block, so they have no loudness.", values$n_no_loudness) else "Every file has a loudness."),
  list(key = "personal_data", label = "Recordings of people", status = "info", detail = "Voices can identify people; check consent before sharing files or results.")
)
cs_publish(list(
  title = "Audio collection profile (duration, loudness, clipping, silence)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(ok),
  summary = sprintf("%d audio files, %.1f s in all; %d silent, %d clipped, %d quiet.", length(ok), values$total_duration_s, values$n_silent, values$n_clipping, values$n_quiet),
  statistics = list(
    list(key = "n_files", label = "Files read", value = length(ok)),
    list(key = "total_duration_s", label = "Total duration (s)", value = values$total_duration_s),
    list(key = "loudness_median", label = "Median loudness (LUFS)", value = values$loudness_median),
    list(key = "n_clipping", label = "Clipped files", value = values$n_clipping)
  ),
  tables = tables,
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "audio_files", path = file.path(out, "audio_files.parquet"), format = "parquet"))
))
Python

7 audio files, 4.8 s in all; 2 silent, 1 clipped, 0 quiet.

Files read
7
Total duration (s)
4.800
Median loudness (LUFS)
−18.395
Clipped files
1

Assumptions

  • Files decode — 2 of 9 listed files could not be read.
  • Measured at each file's own rate — Sample rates: 8000 Hz (2 files), 16000 Hz (4 files), 22050 Hz (1 files).
  • Loudness needs 0.4 s — 1 files are silent or shorter than one 400 ms block, so they have no loudness.
  • Recordings of people — Voices can identify people; check consent before sharing files or results.

Flagged files

FileFlagDuration (s)Loudness (LUFS)Peak (dBFS)Clipped shareSilent share
chirp_loud.wavClipping0.8000−1.044−0.00030.53890
quiet.wavSilent0.6000−54.284−50.48401
silence.wavSilent0.5000——01
speechlike.wavMostly silent1−21.888−7.93000.6154

By label

labelFilesMedian duration (s)Median loudness (LUFS)Flagged
chirp10.8000−1.0441
noise10.6000−26.3420
silence10.5000—1
speech11−21.8881
tone30.6000−14.9031

Files (first 200)

FileDuration (s)Sample rate (Hz)ChannelsLoudness (LUFS)Flag
tone_a.wav0.800016,0001−14.903OK
tone_b.wav0.500022,0502−14.636OK
noise_a.wav0.600016,0001−26.342OK
chirp_loud.wav0.80008,0001−1.044Clipping
quiet.wav0.600016,0001−54.284Silent
silence.wav0.50008,0001—Silent
speechlike.wav116,0001−21.888Mostly silent

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 collection profile (duration, loudness, clipping, silence)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.audio 1.0.0 · spec d5d5727965bc91d8
# 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 describe as ad
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\":false,\"offset_seconds\":0,\"sample_rate\":null}}"), "target/academy-parity/run-8142/describe.audio/grouped_strict/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

# %% Decode and measure each file (channels × samples at the analysis rate)
PATH = "path"
LABEL = "label"
CLIP_LEVEL, SILENCE_DB = 0.99, -50
CLIP_FLAG, SILENCE_FLAG, QUIET, LOUD = 0.0, 0.3, -30, -12
N_WAVES = 2
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
files, clips = [], []
for i, mid in enumerate(media_ids):
    rec = {"row": i, "path": paths[i], "file": os.path.basename(paths[i]), "group": labels[i] if labels else None}
    x = None
    if status[i] is None:
        try:
            x = cs_media.audio(media, [mid])[0]
            rate = float(cs_media.audio_rates(media, [mid])[0])  # each file at its own rate
        except CsError:
            x = None
    if x is None:
        rec["status"] = "unreadable"
        files.append(rec)
        continue
    s = ad.clip_stats(x, rate, CLIP_LEVEL, SILENCE_DB, 0.05, 0.025)
    rec.update(status="ok", sample_rate=rate, **s)
    rec["flag"] = ad.flag(s, CLIP_FLAG, SILENCE_FLAG, QUIET, LOUD)
    files.append(rec)
    if len(clips) < N_WAVES:
        clips.append((rec, x, rate))  # kept only for the waveforms
ok = [r for r in files if r["status"] == "ok"]
if not ok:
    cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an audio file that exists and can be decoded", count=len(files))
warnings = list(warnings)
n_bad = len(files) - len(ok)
if n_bad:
    warnings.append(f"{n_bad} listed files could not be read and are left out.")

# %% Artifact: one row per listed file
out = csml.out_dir("target/academy-parity/run-8142/describe.audio/grouped_strict/out-python")
COLS = ["row", "path", "file", "group", "status", "sample_rate", "duration_s", "channels", "samples", "loudness_lufs", "peak_dbfs", "rms_dbfs", "crest_db",
        "clip_share", "silence_share", "dc_offset", "flag"]
art = pd.DataFrame([{c: r.get(c) for c in COLS} for r in files], columns=COLS)
for c in ("path", "file", "group", "status", "flag"):
    art[c] = art[c].astype("string")
for c in ("sample_rate", "duration_s", "loudness_lufs", "peak_dbfs", "rms_dbfs", "crest_db", "clip_share", "silence_share", "dc_offset"):
    art[c] = pd.to_numeric(art[c], errors="coerce").astype("float64")
for c in ("channels", "samples"):
    art[c] = pd.array([None if pd.isna(v) else int(v) for v in art[c]], dtype="Int64")
art.to_parquet(os.path.join(out, "audio_files.parquet"), index=False)

# %% Summary
def fin(v):
    return v is not None and math.isfinite(v)


D = np.array([r["duration_s"] for r in ok])
L = np.array([r["loudness_lufs"] for r in ok if fin(r["loudness_lufs"])])
flags = [r["flag"] for r in ok]
values = {
    "n_rows": len(files), "n_files": len(ok), "n_unreadable": n_bad,
    "total_duration_s": float(np.sum(D)), "duration_min": float(np.min(D)), "duration_median": float(np.median(D)), "duration_max": float(np.max(D)),
    "n_mono": sum(r["channels"] == 1 for r in ok), "n_stereo": sum(r["channels"] == 2 for r in ok), "n_multichannel": sum(r["channels"] > 2 for r in ok),
    "loudness_median": float(np.median(L)) if len(L) else None, "loudness_min": float(np.min(L)) if len(L) else None,
    "loudness_max": float(np.max(L)) if len(L) else None, "n_no_loudness": len(ok) - len(L),
    "peak_max_dbfs": float(max(r["peak_dbfs"] for r in ok)),
    "clip_share_mean": float(np.mean([r["clip_share"] for r in ok if fin(r["clip_share"])])) if any(fin(r["clip_share"]) for r in ok) else None,
    "silence_share_mean": float(np.mean([r["silence_share"] for r in ok if fin(r["silence_share"])])) if any(fin(r["silence_share"]) for r in ok) else None,
    "n_ok": flags.count("OK"), "n_silent": flags.count("Silent"), "n_clipping": flags.count("Clipping"),
    "n_mostly_silent": flags.count("Mostly silent"), "n_quiet": flags.count("Quiet"), "n_loud": flags.count("Loud"),
    "n_rates": len({r["sample_rate"] for r in ok}),
}
for rate in sorted({r["sample_rate"] for r in ok}):
    values[f"files_at_rate[{int(rate)}]"] = sum(r["sample_rate"] == rate for r in ok)
group_rows = []
if LABEL is not None:
    for g in [str(v) for v in df[LABEL].cat.categories]:
        rs = [r for r in ok if r["group"] == g]
        if not rs:
            continue
        lg = [r["loudness_lufs"] for r in rs if fin(r["loudness_lufs"])]
        values[f"files[{g}]"] = len(rs)
        values[f"duration_median[{g}]"] = float(np.median([r["duration_s"] for r in rs]))
        if lg:
            values[f"loudness_median[{g}]"] = float(np.median(lg))
        group_rows.append({"group": g, "files": len(rs), "duration_median": values[f"duration_median[{g}]"],
                           "loudness_median": values.get(f"loudness_median[{g}]"), "flagged": sum(r["flag"] != "OK" for r in rs)})

# %% Result
FLAG_LEVELS = ["OK", "Silent", "Clipping", "Mostly silent", "Quiet", "Loud", "Empty"]
flagged = [r for r in ok if r["flag"] != "OK"][:50]
tables = [{
    "key": "flagged", "title": "Flagged files",
    "columns": [{"key": "file", "label": "File"}, {"key": "flag", "label": "Flag"}, {"key": "duration_s", "label": "Duration (s)", "type": "number"},
                {"key": "loudness_lufs", "label": "Loudness (LUFS)", "type": "number"}, {"key": "peak_dbfs", "label": "Peak (dBFS)", "type": "number"},
                {"key": "clip_share", "label": "Clipped share", "type": "number"}, {"key": "silence_share", "label": "Silent share", "type": "number"}],
    "rows": [{k: (r[k] if not isinstance(r[k], float) or math.isfinite(r[k]) else None) for k in ("file", "flag", "duration_s", "loudness_lufs", "peak_dbfs", "clip_share", "silence_share")} for r in flagged],
}]
if group_rows:
    tables.append({"key": "groups", "title": f"By {LABEL}", "columns": [
        {"key": "group", "label": LABEL}, {"key": "files", "label": "Files", "type": "integer"}, {"key": "duration_median", "label": "Median duration (s)", "type": "number"},
        {"key": "loudness_median", "label": "Median loudness (LUFS)", "type": "number"}, {"key": "flagged", "label": "Flagged", "type": "integer"}], "rows": group_rows})
tables.append({"key": "files", "title": "Files (first 200)", "columns": [
    {"key": "file", "label": "File"}, {"key": "duration_s", "label": "Duration (s)", "type": "number"}, {"key": "sample_rate", "label": "Sample rate (Hz)", "type": "integer"},
    {"key": "channels", "label": "Channels", "type": "integer"}, {"key": "loudness_lufs", "label": "Loudness (LUFS)", "type": "number"}, {"key": "flag", "label": "Flag"}],
    "rows": [{"file": r["file"], "media_id": media_ids[r["row"]], "duration_s": r["duration_s"], "sample_rate": int(r["sample_rate"]), "channels": r["channels"],
              "loudness_lufs": r["loudness_lufs"] if math.isfinite(r["loudness_lufs"]) else None, "flag": r["flag"]} for r in ok[:200]]})
bad = [r for r in files if r["status"] != "ok"][:50]
if bad:
    tables.append({"key": "unreadable", "title": "Files that could not be read", "columns": [{"key": "file", "label": "File"}, {"key": "path", "label": "Path"}],
                   "rows": [{"file": r["file"], "path": r["path"]} for r in bad]})
charts = []
if len(L):
    charts.append(cs.chart("loudness", "histogram", "Integrated loudness", {"x": cs.col("Loudness (LUFS)", L, "numeric")}, controls={"scale": "count", "kde": False}))
withl = [r for r in ok if fin(r["loudness_lufs"])]
if withl:
    charts.append(cs.chart("levels", "scatter", "Loudness by duration", {
        "x": cs.col("Duration (s)", [r["duration_s"] for r in withl], "numeric"),
        "y": cs.col("Loudness (LUFS)", [r["loudness_lufs"] for r in withl], "numeric"),
        "color": cs.col("Flag", [r["flag"] for r in withl], "categorical", FLAG_LEVELS),
    }, controls={"fit": "none"}))
if N_WAVES > 0:
    t0, t1, lo, hi, rm, trk = [], [], [], [], [], []
    for rec, x, rate in clips:
        e = ad.envelope(x, rate, 600)
        t0 += e["start"]; t1 += e["end"]; lo += e["min"]; hi += e["max"]; rm += e["rms"]; trk += [rec["file"]] * len(e["min"])
    if t0:
        charts.append(cs.chart("waveforms", "waveform", "Waveforms", {
            "time": cs.col("Time (s)", t0, "numeric"), "end": cs.col("End (s)", t1, "numeric"),
            "min": cs.col("Min", lo, "numeric"), "max": cs.col("Max", hi, "numeric"), "rms": cs.col("RMS", rm, "numeric"),
            "track": cs.col("File", trk, "categorical", list(dict.fromkeys(trk))),
        }, controls={"clip": CLIP_LEVEL}))
assumptions = [
    {"key": "decoded", "label": "Files decode", "status": "warn" if n_bad else "pass",
     "detail": f"{n_bad} of {len(files)} listed files could not be read." if n_bad else "Every listed file was decoded."},
    {"key": "native_rate", "label": "Measured at each file's own rate", "status": "info",
     "detail": "Sample rates: " + ", ".join(f"{int(k)} Hz ({v} files)" for k, v in sorted({r['sample_rate']: sum(q['sample_rate'] == r['sample_rate'] for q in ok) for r in ok}.items())) + "."},
    {"key": "short_files", "label": "Loudness needs 0.4 s", "status": "warn" if values["n_no_loudness"] else "pass",
     "detail": f"{values['n_no_loudness']} files are silent or shorter than one 400 ms block, so they have no loudness." if values["n_no_loudness"] else "Every file has a loudness."},
    {"key": "personal_data", "label": "Recordings of people", "status": "info", "detail": "Voices can identify people; check consent before sharing files or results."},
]
cs.publish({
    "title": "Audio collection profile (duration, loudness, clipping, silence)",
    "engine": cs.engine_info("numpy", "pandas", "scipy"),
    "n": len(ok),
    "summary": f"{len(ok)} audio files, {values['total_duration_s']:.1f} s in all; {values['n_silent']} silent, {values['n_clipping']} clipped, {values['n_quiet']} quiet.",
    "statistics": [
        {"key": "n_files", "label": "Files read", "value": len(ok)},
        {"key": "total_duration_s", "label": "Total duration (s)", "value": values["total_duration_s"]},
        {"key": "loudness_median", "label": "Median loudness (LUFS)", "value": values["loudness_median"]},
        {"key": "n_clipping", "label": "Clipped files", "value": values["n_clipping"]},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "audio_files", "path": os.path.join(out, "audio_files.parquet"), "format": "parquet"}],
})

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

With stricter thresholds (silent below −50 dBFS, mostly silent above 30%), 2 files count as silent and 1 as mostly silent: the very quiet tone has crossed the line.

Check yourself

A file's clipped share is 3%. What should you do before training a model on it?

Show the answer

Answer: c

Clipping cuts the tops off the waveform when the sound is recorded. Turning it down afterwards scales the flat tops too; the missing shape can't be recovered.

05

Waveforms and spectrograms

Explore
WaveformHow does a sound's level move over time — where is it loud, silent or clipped?
View data
time (s)end (s)minmaxrmsfile
00.0100−0.01100.01050.0049voice.wav
0.01000.0200−0.01050.01920.0070voice.wav
0.02000.0300−0.02900.02960.0158voice.wav
0.03000.0400−0.04290.04880.0244voice.wav
0.04000.0500−0.07950.06590.0424voice.wav
0.05000.0600−0.10020.10910.0621voice.wav
0.06000.0700−0.12660.13320.0728voice.wav
0.07000.0800−0.17480.18500.1089voice.wav
0.08000.0900−0.20300.21460.1173voice.wav
0.09000.1000−0.25280.23320.1508voice.wav
0.10000.1100−0.28180.28420.1740voice.wav
0.11000.1200−0.29960.30860.1687voice.wav
0.12000.1300−0.33560.34310.2194voice.wav
0.13000.1400−0.35990.36100.2046voice.wav
0.14000.1500−0.38070.37220.2363voice.wav
0.15000.1600−0.38540.38130.2424voice.wav
0.16000.1700−0.38680.39470.2146voice.wav
0.17000.1800−0.38270.38200.2530voice.wav
0.18000.1900−0.37830.37130.2146voice.wav
0.19000.2000−0.36300.35660.2260voice.wav
0.20000.2100−0.33390.34410.2115voice.wav
0.21000.2200−0.32000.30540.1700voice.wav
0.22000.2300−0.29400.27940.1817voice.wav
0.23000.2400−0.23870.23960.1374voice.wav
0.24000.2500−0.21940.20970.1304voice.wav
0.25000.2600−0.16180.18510.1060voice.wav
0.26000.2700−0.13960.13000.0726voice.wav
0.27000.2800−0.11930.11020.0654voice.wav
0.28000.2900−0.06380.07600.0383voice.wav
0.29000.3000−0.05640.04010.0272voice.wav
0.30000.3100−0.01980.03320.0138voice.wav
0.31000.3200−0.01810.01750.0070voice.wav
0.32000.3300−0.00500.00620.0032voice.wav
0.33000.3400−0.00720.00850.0038voice.wav
0.34000.3500−0.00920.01130.0047voice.wav
0.35000.3600−0.01210.01130.0049voice.wav
0.36000.3700−0.01100.01010.0045voice.wav
0.37000.3800−0.01120.00990.0048voice.wav
0.38000.3900−0.01100.00750.0039voice.wav
0.39000.4000−0.00890.00950.0041voice.wav
0.40000.4100−0.00830.01140.0046voice.wav
0.41000.4200−0.00860.00810.0037voice.wav
0.42000.4300−0.00900.00730.0037voice.wav
0.43000.4400−0.01120.00880.0047voice.wav
0.44000.4500−0.01000.00580.0037voice.wav
0.45000.4600−0.01040.00950.0041voice.wav
0.46000.4700−0.00870.00750.0045voice.wav
0.47000.4800−0.00790.00920.0042voice.wav
0.48000.4900−0.00930.00710.0041voice.wav
0.49000.5000−0.01210.01000.0043voice.wav
0.50000.5100−0.00770.00820.0041voice.wav
0.51000.5200−0.00870.00720.0043voice.wav
0.52000.5300−0.00770.01060.0042voice.wav
0.53000.5400−0.00770.00850.0041voice.wav
0.54000.5500−0.00760.00950.0035voice.wav
0.55000.5600−0.00890.01170.0046voice.wav
0.56000.5700−0.00710.00630.0028voice.wav
0.57000.5800−0.00780.00820.0038voice.wav
0.58000.5900−0.01000.00610.0034voice.wav
0.59000.6000−0.00760.01170.0045voice.wav

First 60 of 900 rows.

A waveform draws, for each short run of samples, the lowest and highest value (the light band) and the RMS level (the dark band). Gaps near zero are silence; red marks show clipping.

SpectrogramWhich frequencies does a sound contain, and how do they change over time?
View data
time (s)frequency (Hz)level (dB)
00−68.430
0125−76.390
0250−20.350
0375−35.780
0500−32.350
0625−20.770
0750−47.780
0875−75.390
01,000−76.960
01,125−71.250
01,250−67.330
01,375−66.010
01,500−75.260
01,625−73.530
01,750−66.130
01,875−70.830
02,000−71.560
02,125−70.790
02,250−69.680
02,375−68.450
02,500−67.370
02,625−71.330
02,750−68.370
02,875−74.050
03,000−71.900
03,125−72.900
03,250−74.640
03,375−71.930
03,500−73.040
03,625−73.050
03,750−74
03,875−74.830
04,000−67.050
04,125−69.880
04,250−73.400
04,375−71.700
04,500−73.500
04,625−76.740
04,750−63.920
04,875−75.910
05,000−78.920
05,125−71.570
05,250−71.960
05,375−71.080
05,500−71.300
05,625−73.990
05,750−69.030
05,875−73.290
06,000−72.170
06,125−70.240
06,250−66.460
06,375−70.340
06,500−79.360
06,625−72.540
06,750−68.210
06,875−72.770
07,000−71.140
07,125−63.890
07,250−69.380
07,375−68.470

First 60 of 8125 rows.

A spectrogramSpectrogramA picture of sound: time across, frequency up, brightness for level; tones are lines, noise is a wash, clicks are vertical stripes. cuts the sound into short overlapping frames (the STFTShort-time Fourier transform (STFT)A sound cut into short overlapping windowed frames, each turned into frequencies: the basis of spectrograms and most audio features.) and shows each frame's frequencies: time across, frequency up, brighter is louder. A steady tone is a horizontal line, its harmonics are parallel lines above it, noise is a wash.

Check yourself

You double the frame length of a spectrogram from 512 to 1024 samples. What changes?

Show the answer

Answer: a

A longer frame holds more cycles of each tone, so frequencies are resolved more finely, but everything inside one frame is averaged together in time. That trade-off is fixed: compare spectrograms only at the same settings.

06

A row of numbers per file

In the app

Most methods need one row per file and numbers in columns. Audio features turns each file into such a row.

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.

Each file became 39 numbers: the mean and spread over frames of 13 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. (the overall shape of the spectrum, computed 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.), the spectral centroid, bandwidth, rolloff and flatness, the RMS level and the zero-crossing rate, plus the file's loudness. Save the table as a dataset to cluster the files, train a classifier or look for unusual recordings.

Check yourself

Why do sound classifiers so often start from MFCC means and standard deviations?

Show the answer

Answer: b

MFCCs describe the shape of the log mel spectrum, which captures timbre (what makes a violin sound unlike a voice). Summaries over frames drop the timing, so they're compact but can't tell "da-dum" from "dum-da".

07

Keep the time with windows

Checkpoint

A mean over a whole file hides when things happen. With one row per window each quarter second gets its own row:

Audio features (MFCC, spectral shape, chroma, loudness)Recorded · Python and R agreeRecorded 2026-11-25 · 21 values compared
R

7 files described by 13 features in 29 rows.

Files read
7
Rows in the table
29
Features
13

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 window is summarized on its own.

Feature table (first rows and columns)

media_idpathfilelabelwindowstart_send_smfcc_1_meanmfcc_2_meanmfcc_3_meanmfcc_4_meanmfcc_5_meanmfcc_6_meanmfcc_7_meanmfcc_8_mean
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone000.2500−374.1825.4256.2142.943−1.579−4.190−5.939−6.115
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone10.12500.3750−354.3052.89927.58111.378−6.144−19.507−27.644−29.338
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone20.25000.5000−340.8468.26738.61216.048−8.544−28.089−40.126−42.751
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone30.37500.6250−340.8468.26738.61216.048−8.544−28.089−40.126−42.751
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone40.50000.7500−340.8468.26738.61216.048−8.544−28.089−40.126−42.751
2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920aud1_clips/tone_b.wavtone_b.wavtone000.2500−222.0729.9418.669−11.999−25.920−26.574−17.573−0.7668
2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920aud1_clips/tone_b.wavtone_b.wavtone10.12500.3750−222.2831.2908.134−12.813−25.031−26.440−16.481−0.7517
2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920aud1_clips/tone_b.wavtone_b.wavtone20.25000.5000−221.4531.6618.083−12.736−24.491−26.227−18.009−1.489
0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5aud1_clips/noise_a.wavnoise_a.wavnoise000.2500−209.09134.19−25.516−1.882−5.50410.794−4.098−1.386
0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5aud1_clips/noise_a.wavnoise_a.wavnoise10.12500.3750−210.13137.05−26.998−1.242−7.14511.999−4.515−0.9428
0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5aud1_clips/noise_a.wavnoise_a.wavnoise20.25000.5000−207.62135.70−26.970−2.164−6.49010.815−4.026−1.048
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp000.2500−161.4877.449−31.64427.305−20.296−19.750−13.687−22.613
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp10.12500.3750−163.3261.347−47.6609.464−39.690−26.2625.831−0.5483
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp20.25000.5000−162.2453.893−58.7701.635−36.12613.40231.016−5.582
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp30.37500.6250−162.6545.275−62.8228.682−12.65733.9394.118−30.801
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp40.50000.7500−178.0333.527−68.49628.9430.927113.279−11.171−25.342
600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891aud1_clips/quiet.wavquiet.wavtone000.2500−539.4667.21149.21133.43620.0601.288−12.820−5.981
600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891aud1_clips/quiet.wavquiet.wavtone10.12500.3750−539.4667.21149.21133.43620.0601.288−12.820−5.981
600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891aud1_clips/quiet.wavquiet.wavtone20.25000.5000−539.4667.21149.21133.43620.0601.288−12.820−5.981
399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84aud1_clips/silence.wavsilence.wavsilence000.2500−632.461.332e-156.795e-14−5.773e-144.663e-14−9.437e-143.908e-144.519e-14
399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84aud1_clips/silence.wavsilence.wavsilence10.12500.3750−632.461.332e-156.795e-14−5.773e-144.663e-14−9.437e-143.908e-144.519e-14
399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84aud1_clips/silence.wavsilence.wavsilence20.25000.5000−632.461.332e-156.795e-14−5.773e-144.663e-14−9.437e-143.908e-144.519e-14
4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485aud1_clips/speechlike.wavspeechlike.wavspeech000.2500−250.0152.38435.00515.5033.9934.1569.3397.542
4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485aud1_clips/speechlike.wavspeechlike.wavspeech10.12500.3750−279.4914.3419.3784.3611.5421.4682.9600.4343
4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485aud1_clips/speechlike.wavspeechlike.wavspeech20.25000.5000−296.28−2.4250.4222−0.05500.21150.23900.3478−1.327

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 e1a7f3793c6c40ff
# 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/windows_mfcc_only/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 = FALSE, chroma = FALSE,
        energy = FALSE, loudness = FALSE)
SETS <- names(on)[on]
STATS <- list(mean_sd = c("mean", "sd"), mean = "mean", all = c("mean", "sd", "min", "max"))[["mean"]]
N_MFCC <- 13; N_MELS <- 40; N_FFT <- 512; HOP <- 160
PER_WINDOW <- TRUE
WIN <- 0.25; WIN_HOP <- 0.125
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/windows_mfcc_only/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 13 features in 29 rows.

Files read
7
Rows in the table
29
Features
13

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 window is summarized on its own.

Feature table (first rows and columns)

media_idpathfilelabelwindowstart_send_smfcc_1_meanmfcc_2_meanmfcc_3_meanmfcc_4_meanmfcc_5_meanmfcc_6_meanmfcc_7_meanmfcc_8_mean
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone000.2500−374.1825.4256.2142.943−1.579−4.190−5.939−6.115
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone10.12500.3750−354.3052.89927.58111.378−6.144−19.507−27.644−29.338
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone20.25000.5000−340.8468.26738.61216.048−8.544−28.089−40.126−42.751
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone30.37500.6250−340.8468.26738.61216.048−8.544−28.089−40.126−42.751
dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943aud1_clips/tone_a.wavtone_a.wavtone40.50000.7500−340.8468.26738.61216.048−8.544−28.089−40.126−42.751
2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920aud1_clips/tone_b.wavtone_b.wavtone000.2500−222.0729.9418.669−11.999−25.920−26.574−17.573−0.7668
2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920aud1_clips/tone_b.wavtone_b.wavtone10.12500.3750−222.2831.2908.134−12.813−25.031−26.440−16.481−0.7517
2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920aud1_clips/tone_b.wavtone_b.wavtone20.25000.5000−221.4531.6618.083−12.736−24.491−26.227−18.009−1.489
0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5aud1_clips/noise_a.wavnoise_a.wavnoise000.2500−209.09134.19−25.516−1.882−5.50410.794−4.098−1.386
0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5aud1_clips/noise_a.wavnoise_a.wavnoise10.12500.3750−210.13137.05−26.998−1.242−7.14511.999−4.515−0.9428
0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5aud1_clips/noise_a.wavnoise_a.wavnoise20.25000.5000−207.62135.70−26.970−2.164−6.49010.815−4.026−1.048
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp000.2500−161.4877.449−31.64427.305−20.296−19.750−13.687−22.613
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp10.12500.3750−163.3261.347−47.6609.464−39.690−26.2625.831−0.5483
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp20.25000.5000−162.2453.893−58.7701.635−36.12613.40231.016−5.582
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp30.37500.6250−162.6545.275−62.8228.682−12.65733.9394.118−30.801
07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402aud1_clips/chirp_loud.wavchirp_loud.wavchirp40.50000.7500−178.0333.527−68.49628.9430.927113.279−11.171−25.342
600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891aud1_clips/quiet.wavquiet.wavtone000.2500−539.4667.21149.21133.43620.0601.288−12.820−5.981
600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891aud1_clips/quiet.wavquiet.wavtone10.12500.3750−539.4667.21149.21133.43620.0601.288−12.820−5.981
600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891aud1_clips/quiet.wavquiet.wavtone20.25000.5000−539.4667.21149.21133.43620.0601.288−12.820−5.981
399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84aud1_clips/silence.wavsilence.wavsilence000.2500−632.461.332e-156.795e-14−5.773e-144.663e-14−9.437e-143.908e-144.519e-14
399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84aud1_clips/silence.wavsilence.wavsilence10.12500.3750−632.461.332e-156.795e-14−5.773e-144.663e-14−9.437e-143.908e-144.519e-14
399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84aud1_clips/silence.wavsilence.wavsilence20.25000.5000−632.461.332e-156.795e-14−5.773e-144.663e-14−9.437e-143.908e-144.519e-14
4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485aud1_clips/speechlike.wavspeechlike.wavspeech000.2500−250.0152.38435.00515.5033.9934.1569.3397.542
4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485aud1_clips/speechlike.wavspeechlike.wavspeech10.12500.3750−279.4914.3419.3784.3611.5421.4682.9600.4343
4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485aud1_clips/speechlike.wavspeechlike.wavspeech20.25000.5000−296.28−2.4250.4222−0.05500.21150.23900.3478−1.327

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 e1a7f3793c6c40ff
# 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/windows_mfcc_only/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", False), ("chroma", False),
                        ("energy", False), ("loudness", False)) if on]
STATS = {"mean_sd": ["mean", "sd"], "mean": ["mean"], "all": ["mean", "sd", "min", "max"]}["mean"]
N_MFCC, N_MELS, N_FFT, HOP = 13, 40, 512, 160
PER_WINDOW = True
WIN, WIN_HOP = 0.25, 0.125
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/windows_mfcc_only/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.

The seven files became 29 rows. When you train on windows, keep all windows of one file on the same side of the split, or the model is tested on near-copies of what it trained on.

Check yourself

You cut 200 recordings into one-second windows and split the windows at random into training and test sets. Why is the test score likely too good?

Show the answer

Answer: b

Windows of one recording share the speaker, room and microphone. Group the split by recording (or speaker) so the test set holds recordings the model has never heard.

Concepts in this lesson