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.
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
Recordings are long lists of numbers
ReadA 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.
A small test collection
In the appThe 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.
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
| File | Flag | Duration (s) | Loudness (LUFS) | Peak (dBFS) | Clipped share | Silent share |
|---|---|---|---|---|---|---|
| chirp_loud.wav | Clipping | 0.8000 | −1.044 | −0.0003 | 0.5331 | 0 |
| quiet.wav | Quiet | 0.6000 | −54.284 | −50.484 | 0 | 0 |
| silence.wav | Silent | 0.5000 | — | — | 0 | 1 |
Files (first 200)
| File | Duration (s) | Sample rate (Hz) | Channels | Loudness (LUFS) | Flag |
|---|---|---|---|---|---|
| tone_a.wav | 0.8000 | 16,000 | 1 | −14.903 | OK |
| tone_b.wav | 0.5000 | 22,050 | 2 | −14.636 | OK |
| noise_a.wav | 0.6000 | 16,000 | 1 | −26.342 | OK |
| chirp_loud.wav | 0.8000 | 8,000 | 1 | −1.044 | Clipping |
| quiet.wav | 0.6000 | 16,000 | 1 | −54.284 | Quiet |
| silence.wav | 0.5000 | 8,000 | 1 | — | Silent |
| speechlike.wav | 1 | 16,000 | 1 | −21.888 | OK |
Files that could not be read
| File | Path |
|---|---|
| notes.wav | aud1_clips/notes.wav |
| not_there.wav | aud1_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"))
))
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
| File | Flag | Duration (s) | Loudness (LUFS) | Peak (dBFS) | Clipped share | Silent share |
|---|---|---|---|---|---|---|
| chirp_loud.wav | Clipping | 0.8000 | −1.044 | −0.0003 | 0.5331 | 0 |
| quiet.wav | Quiet | 0.6000 | −54.284 | −50.484 | 0 | 0 |
| silence.wav | Silent | 0.5000 | — | — | 0 | 1 |
Files (first 200)
| File | Duration (s) | Sample rate (Hz) | Channels | Loudness (LUFS) | Flag |
|---|---|---|---|---|---|
| tone_a.wav | 0.8000 | 16,000 | 1 | −14.903 | OK |
| tone_b.wav | 0.5000 | 22,050 | 2 | −14.636 | OK |
| noise_a.wav | 0.6000 | 16,000 | 1 | −26.342 | OK |
| chirp_loud.wav | 0.8000 | 8,000 | 1 | −1.044 | Clipping |
| quiet.wav | 0.6000 | 16,000 | 1 | −54.284 | Quiet |
| silence.wav | 0.5000 | 8,000 | 1 | — | Silent |
| speechlike.wav | 1 | 16,000 | 1 | −21.888 | OK |
Files that could not be read
| File | Path |
|---|---|
| notes.wav | aud1_clips/notes.wav |
| not_there.wav | aud1_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.
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.
Flags
ExploreEach 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.
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
| File | Flag | Duration (s) | Loudness (LUFS) | Peak (dBFS) | Clipped share | Silent share |
|---|---|---|---|---|---|---|
| chirp_loud.wav | Clipping | 0.8000 | −1.044 | −0.0003 | 0.5389 | 0 |
| quiet.wav | Silent | 0.6000 | −54.284 | −50.484 | 0 | 1 |
| silence.wav | Silent | 0.5000 | — | — | 0 | 1 |
| speechlike.wav | Mostly silent | 1 | −21.888 | −7.930 | 0 | 0.6154 |
By label
| label | Files | Median duration (s) | Median loudness (LUFS) | Flagged |
|---|---|---|---|---|
| chirp | 1 | 0.8000 | −1.044 | 1 |
| noise | 1 | 0.6000 | −26.342 | 0 |
| silence | 1 | 0.5000 | — | 1 |
| speech | 1 | 1 | −21.888 | 1 |
| tone | 3 | 0.6000 | −14.903 | 1 |
Files (first 200)
| File | Duration (s) | Sample rate (Hz) | Channels | Loudness (LUFS) | Flag |
|---|---|---|---|---|---|
| tone_a.wav | 0.8000 | 16,000 | 1 | −14.903 | OK |
| tone_b.wav | 0.5000 | 22,050 | 2 | −14.636 | OK |
| noise_a.wav | 0.6000 | 16,000 | 1 | −26.342 | OK |
| chirp_loud.wav | 0.8000 | 8,000 | 1 | −1.044 | Clipping |
| quiet.wav | 0.6000 | 16,000 | 1 | −54.284 | Silent |
| silence.wav | 0.5000 | 8,000 | 1 | — | Silent |
| speechlike.wav | 1 | 16,000 | 1 | −21.888 | Mostly silent |
Files that could not be read
| File | Path |
|---|---|
| notes.wav | aud1_clips/notes.wav |
| not_there.wav | aud1_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"))
))
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
| File | Flag | Duration (s) | Loudness (LUFS) | Peak (dBFS) | Clipped share | Silent share |
|---|---|---|---|---|---|---|
| chirp_loud.wav | Clipping | 0.8000 | −1.044 | −0.0003 | 0.5389 | 0 |
| quiet.wav | Silent | 0.6000 | −54.284 | −50.484 | 0 | 1 |
| silence.wav | Silent | 0.5000 | — | — | 0 | 1 |
| speechlike.wav | Mostly silent | 1 | −21.888 | −7.930 | 0 | 0.6154 |
By label
| label | Files | Median duration (s) | Median loudness (LUFS) | Flagged |
|---|---|---|---|---|
| chirp | 1 | 0.8000 | −1.044 | 1 |
| noise | 1 | 0.6000 | −26.342 | 0 |
| silence | 1 | 0.5000 | — | 1 |
| speech | 1 | 1 | −21.888 | 1 |
| tone | 3 | 0.6000 | −14.903 | 1 |
Files (first 200)
| File | Duration (s) | Sample rate (Hz) | Channels | Loudness (LUFS) | Flag |
|---|---|---|---|---|---|
| tone_a.wav | 0.8000 | 16,000 | 1 | −14.903 | OK |
| tone_b.wav | 0.5000 | 22,050 | 2 | −14.636 | OK |
| noise_a.wav | 0.6000 | 16,000 | 1 | −26.342 | OK |
| chirp_loud.wav | 0.8000 | 8,000 | 1 | −1.044 | Clipping |
| quiet.wav | 0.6000 | 16,000 | 1 | −54.284 | Silent |
| silence.wav | 0.5000 | 8,000 | 1 | — | Silent |
| speechlike.wav | 1 | 16,000 | 1 | −21.888 | Mostly silent |
Files that could not be read
| File | Path |
|---|---|
| notes.wav | aud1_clips/notes.wav |
| not_there.wav | aud1_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.
Waveforms and spectrograms
ExploreView data
| time (s) | end (s) | min | max | rms | file |
|---|---|---|---|---|---|
| 0 | 0.0100 | −0.0110 | 0.0105 | 0.0049 | voice.wav |
| 0.0100 | 0.0200 | −0.0105 | 0.0192 | 0.0070 | voice.wav |
| 0.0200 | 0.0300 | −0.0290 | 0.0296 | 0.0158 | voice.wav |
| 0.0300 | 0.0400 | −0.0429 | 0.0488 | 0.0244 | voice.wav |
| 0.0400 | 0.0500 | −0.0795 | 0.0659 | 0.0424 | voice.wav |
| 0.0500 | 0.0600 | −0.1002 | 0.1091 | 0.0621 | voice.wav |
| 0.0600 | 0.0700 | −0.1266 | 0.1332 | 0.0728 | voice.wav |
| 0.0700 | 0.0800 | −0.1748 | 0.1850 | 0.1089 | voice.wav |
| 0.0800 | 0.0900 | −0.2030 | 0.2146 | 0.1173 | voice.wav |
| 0.0900 | 0.1000 | −0.2528 | 0.2332 | 0.1508 | voice.wav |
| 0.1000 | 0.1100 | −0.2818 | 0.2842 | 0.1740 | voice.wav |
| 0.1100 | 0.1200 | −0.2996 | 0.3086 | 0.1687 | voice.wav |
| 0.1200 | 0.1300 | −0.3356 | 0.3431 | 0.2194 | voice.wav |
| 0.1300 | 0.1400 | −0.3599 | 0.3610 | 0.2046 | voice.wav |
| 0.1400 | 0.1500 | −0.3807 | 0.3722 | 0.2363 | voice.wav |
| 0.1500 | 0.1600 | −0.3854 | 0.3813 | 0.2424 | voice.wav |
| 0.1600 | 0.1700 | −0.3868 | 0.3947 | 0.2146 | voice.wav |
| 0.1700 | 0.1800 | −0.3827 | 0.3820 | 0.2530 | voice.wav |
| 0.1800 | 0.1900 | −0.3783 | 0.3713 | 0.2146 | voice.wav |
| 0.1900 | 0.2000 | −0.3630 | 0.3566 | 0.2260 | voice.wav |
| 0.2000 | 0.2100 | −0.3339 | 0.3441 | 0.2115 | voice.wav |
| 0.2100 | 0.2200 | −0.3200 | 0.3054 | 0.1700 | voice.wav |
| 0.2200 | 0.2300 | −0.2940 | 0.2794 | 0.1817 | voice.wav |
| 0.2300 | 0.2400 | −0.2387 | 0.2396 | 0.1374 | voice.wav |
| 0.2400 | 0.2500 | −0.2194 | 0.2097 | 0.1304 | voice.wav |
| 0.2500 | 0.2600 | −0.1618 | 0.1851 | 0.1060 | voice.wav |
| 0.2600 | 0.2700 | −0.1396 | 0.1300 | 0.0726 | voice.wav |
| 0.2700 | 0.2800 | −0.1193 | 0.1102 | 0.0654 | voice.wav |
| 0.2800 | 0.2900 | −0.0638 | 0.0760 | 0.0383 | voice.wav |
| 0.2900 | 0.3000 | −0.0564 | 0.0401 | 0.0272 | voice.wav |
| 0.3000 | 0.3100 | −0.0198 | 0.0332 | 0.0138 | voice.wav |
| 0.3100 | 0.3200 | −0.0181 | 0.0175 | 0.0070 | voice.wav |
| 0.3200 | 0.3300 | −0.0050 | 0.0062 | 0.0032 | voice.wav |
| 0.3300 | 0.3400 | −0.0072 | 0.0085 | 0.0038 | voice.wav |
| 0.3400 | 0.3500 | −0.0092 | 0.0113 | 0.0047 | voice.wav |
| 0.3500 | 0.3600 | −0.0121 | 0.0113 | 0.0049 | voice.wav |
| 0.3600 | 0.3700 | −0.0110 | 0.0101 | 0.0045 | voice.wav |
| 0.3700 | 0.3800 | −0.0112 | 0.0099 | 0.0048 | voice.wav |
| 0.3800 | 0.3900 | −0.0110 | 0.0075 | 0.0039 | voice.wav |
| 0.3900 | 0.4000 | −0.0089 | 0.0095 | 0.0041 | voice.wav |
| 0.4000 | 0.4100 | −0.0083 | 0.0114 | 0.0046 | voice.wav |
| 0.4100 | 0.4200 | −0.0086 | 0.0081 | 0.0037 | voice.wav |
| 0.4200 | 0.4300 | −0.0090 | 0.0073 | 0.0037 | voice.wav |
| 0.4300 | 0.4400 | −0.0112 | 0.0088 | 0.0047 | voice.wav |
| 0.4400 | 0.4500 | −0.0100 | 0.0058 | 0.0037 | voice.wav |
| 0.4500 | 0.4600 | −0.0104 | 0.0095 | 0.0041 | voice.wav |
| 0.4600 | 0.4700 | −0.0087 | 0.0075 | 0.0045 | voice.wav |
| 0.4700 | 0.4800 | −0.0079 | 0.0092 | 0.0042 | voice.wav |
| 0.4800 | 0.4900 | −0.0093 | 0.0071 | 0.0041 | voice.wav |
| 0.4900 | 0.5000 | −0.0121 | 0.0100 | 0.0043 | voice.wav |
| 0.5000 | 0.5100 | −0.0077 | 0.0082 | 0.0041 | voice.wav |
| 0.5100 | 0.5200 | −0.0087 | 0.0072 | 0.0043 | voice.wav |
| 0.5200 | 0.5300 | −0.0077 | 0.0106 | 0.0042 | voice.wav |
| 0.5300 | 0.5400 | −0.0077 | 0.0085 | 0.0041 | voice.wav |
| 0.5400 | 0.5500 | −0.0076 | 0.0095 | 0.0035 | voice.wav |
| 0.5500 | 0.5600 | −0.0089 | 0.0117 | 0.0046 | voice.wav |
| 0.5600 | 0.5700 | −0.0071 | 0.0063 | 0.0028 | voice.wav |
| 0.5700 | 0.5800 | −0.0078 | 0.0082 | 0.0038 | voice.wav |
| 0.5800 | 0.5900 | −0.0100 | 0.0061 | 0.0034 | voice.wav |
| 0.5900 | 0.6000 | −0.0076 | 0.0117 | 0.0045 | voice.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.
View data
| time (s) | frequency (Hz) | level (dB) |
|---|---|---|
| 0 | 0 | −68.430 |
| 0 | 125 | −76.390 |
| 0 | 250 | −20.350 |
| 0 | 375 | −35.780 |
| 0 | 500 | −32.350 |
| 0 | 625 | −20.770 |
| 0 | 750 | −47.780 |
| 0 | 875 | −75.390 |
| 0 | 1,000 | −76.960 |
| 0 | 1,125 | −71.250 |
| 0 | 1,250 | −67.330 |
| 0 | 1,375 | −66.010 |
| 0 | 1,500 | −75.260 |
| 0 | 1,625 | −73.530 |
| 0 | 1,750 | −66.130 |
| 0 | 1,875 | −70.830 |
| 0 | 2,000 | −71.560 |
| 0 | 2,125 | −70.790 |
| 0 | 2,250 | −69.680 |
| 0 | 2,375 | −68.450 |
| 0 | 2,500 | −67.370 |
| 0 | 2,625 | −71.330 |
| 0 | 2,750 | −68.370 |
| 0 | 2,875 | −74.050 |
| 0 | 3,000 | −71.900 |
| 0 | 3,125 | −72.900 |
| 0 | 3,250 | −74.640 |
| 0 | 3,375 | −71.930 |
| 0 | 3,500 | −73.040 |
| 0 | 3,625 | −73.050 |
| 0 | 3,750 | −74 |
| 0 | 3,875 | −74.830 |
| 0 | 4,000 | −67.050 |
| 0 | 4,125 | −69.880 |
| 0 | 4,250 | −73.400 |
| 0 | 4,375 | −71.700 |
| 0 | 4,500 | −73.500 |
| 0 | 4,625 | −76.740 |
| 0 | 4,750 | −63.920 |
| 0 | 4,875 | −75.910 |
| 0 | 5,000 | −78.920 |
| 0 | 5,125 | −71.570 |
| 0 | 5,250 | −71.960 |
| 0 | 5,375 | −71.080 |
| 0 | 5,500 | −71.300 |
| 0 | 5,625 | −73.990 |
| 0 | 5,750 | −69.030 |
| 0 | 5,875 | −73.290 |
| 0 | 6,000 | −72.170 |
| 0 | 6,125 | −70.240 |
| 0 | 6,250 | −66.460 |
| 0 | 6,375 | −70.340 |
| 0 | 6,500 | −79.360 |
| 0 | 6,625 | −72.540 |
| 0 | 6,750 | −68.210 |
| 0 | 6,875 | −72.770 |
| 0 | 7,000 | −71.140 |
| 0 | 7,125 | −63.890 |
| 0 | 7,250 | −69.380 |
| 0 | 7,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.
A row of numbers per file
In the appMost methods need one row per file and numbers in columns. Audio features turns each file into such a row.
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_id | path | file | label | mfcc_1_mean | mfcc_1_sd | mfcc_2_mean | mfcc_2_sd | mfcc_3_mean | mfcc_3_sd | mfcc_4_mean | mfcc_4_sd |
|---|---|---|---|---|---|---|---|---|---|---|---|
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | −371.29 | 46.888 | 49.617 | 29.650 | 31.091 | 18.454 | 12.786 | 7.417 |
| 2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920 | aud1_clips/tone_b.wav | tone_b.wav | tone | −226.74 | 18.631 | 26.966 | 14.544 | 8.312 | 3.411 | −12.151 | 2.866 |
| 0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5 | aud1_clips/noise_a.wav | noise_a.wav | noise | −209.81 | 3.530 | 137.25 | 5.598 | −27.548 | 3.239 | −1.640 | 3.268 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | −171.72 | 23.807 | 49.762 | 25.357 | −54.399 | 21.888 | 20.519 | 22.270 |
| 600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891 | aud1_clips/quiet.wav | quiet.wav | tone | −548.88 | 27.252 | 63.250 | 11.117 | 51.510 | 6.596 | 35.228 | 5.031 |
| 399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84 | aud1_clips/silence.wav | silence.wav | silence | −632.46 | 5.684e-13 | 1.332e-15 | 0 | 6.795e-14 | 0 | −5.773e-14 | 0 |
| 4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485 | aud1_clips/speechlike.wav | speechlike.wav | speech | −272.40 | 33.527 | 25.967 | 40.329 | 17.862 | 24.834 | 7.479 | 10.073 |
Files that could not be read
| File | Path |
|---|---|
| notes.wav | aud1_clips/notes.wav |
| not_there.wav | aud1_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"))
))
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_id | path | file | label | mfcc_1_mean | mfcc_1_sd | mfcc_2_mean | mfcc_2_sd | mfcc_3_mean | mfcc_3_sd | mfcc_4_mean | mfcc_4_sd |
|---|---|---|---|---|---|---|---|---|---|---|---|
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | −371.29 | 46.888 | 49.617 | 29.650 | 31.091 | 18.454 | 12.786 | 7.417 |
| 2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920 | aud1_clips/tone_b.wav | tone_b.wav | tone | −226.74 | 18.631 | 26.966 | 14.544 | 8.312 | 3.411 | −12.151 | 2.866 |
| 0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5 | aud1_clips/noise_a.wav | noise_a.wav | noise | −209.81 | 3.530 | 137.25 | 5.598 | −27.548 | 3.239 | −1.640 | 3.268 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | −171.72 | 23.807 | 49.762 | 25.357 | −54.399 | 21.888 | 20.519 | 22.270 |
| 600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891 | aud1_clips/quiet.wav | quiet.wav | tone | −548.88 | 27.252 | 63.250 | 11.117 | 51.510 | 6.596 | 35.228 | 5.031 |
| 399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84 | aud1_clips/silence.wav | silence.wav | silence | −632.46 | 0 | 1.332e-15 | 0 | 6.795e-14 | 0 | −5.773e-14 | 0 |
| 4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485 | aud1_clips/speechlike.wav | speechlike.wav | speech | −272.40 | 33.527 | 25.967 | 40.329 | 17.862 | 24.834 | 7.479 | 10.073 |
Files that could not be read
| File | Path |
|---|---|
| notes.wav | aud1_clips/notes.wav |
| not_there.wav | aud1_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".
Keep the time with windows
CheckpointA mean over a whole file hides when things happen. With one row per window each quarter second gets its own row:
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_id | path | file | label | window | start_s | end_s | mfcc_1_mean | mfcc_2_mean | mfcc_3_mean | mfcc_4_mean | mfcc_5_mean | mfcc_6_mean | mfcc_7_mean | mfcc_8_mean |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | 0 | 0 | 0.2500 | −374.18 | 25.425 | 6.214 | 2.943 | −1.579 | −4.190 | −5.939 | −6.115 |
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | 1 | 0.1250 | 0.3750 | −354.30 | 52.899 | 27.581 | 11.378 | −6.144 | −19.507 | −27.644 | −29.338 |
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | 2 | 0.2500 | 0.5000 | −340.84 | 68.267 | 38.612 | 16.048 | −8.544 | −28.089 | −40.126 | −42.751 |
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | 3 | 0.3750 | 0.6250 | −340.84 | 68.267 | 38.612 | 16.048 | −8.544 | −28.089 | −40.126 | −42.751 |
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | 4 | 0.5000 | 0.7500 | −340.84 | 68.267 | 38.612 | 16.048 | −8.544 | −28.089 | −40.126 | −42.751 |
| 2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920 | aud1_clips/tone_b.wav | tone_b.wav | tone | 0 | 0 | 0.2500 | −222.07 | 29.941 | 8.669 | −11.999 | −25.920 | −26.574 | −17.573 | −0.7668 |
| 2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920 | aud1_clips/tone_b.wav | tone_b.wav | tone | 1 | 0.1250 | 0.3750 | −222.28 | 31.290 | 8.134 | −12.813 | −25.031 | −26.440 | −16.481 | −0.7517 |
| 2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920 | aud1_clips/tone_b.wav | tone_b.wav | tone | 2 | 0.2500 | 0.5000 | −221.45 | 31.661 | 8.083 | −12.736 | −24.491 | −26.227 | −18.009 | −1.489 |
| 0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5 | aud1_clips/noise_a.wav | noise_a.wav | noise | 0 | 0 | 0.2500 | −209.09 | 134.19 | −25.516 | −1.882 | −5.504 | 10.794 | −4.098 | −1.386 |
| 0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5 | aud1_clips/noise_a.wav | noise_a.wav | noise | 1 | 0.1250 | 0.3750 | −210.13 | 137.05 | −26.998 | −1.242 | −7.145 | 11.999 | −4.515 | −0.9428 |
| 0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5 | aud1_clips/noise_a.wav | noise_a.wav | noise | 2 | 0.2500 | 0.5000 | −207.62 | 135.70 | −26.970 | −2.164 | −6.490 | 10.815 | −4.026 | −1.048 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | 0 | 0 | 0.2500 | −161.48 | 77.449 | −31.644 | 27.305 | −20.296 | −19.750 | −13.687 | −22.613 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | 1 | 0.1250 | 0.3750 | −163.32 | 61.347 | −47.660 | 9.464 | −39.690 | −26.262 | 5.831 | −0.5483 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | 2 | 0.2500 | 0.5000 | −162.24 | 53.893 | −58.770 | 1.635 | −36.126 | 13.402 | 31.016 | −5.582 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | 3 | 0.3750 | 0.6250 | −162.65 | 45.275 | −62.822 | 8.682 | −12.657 | 33.939 | 4.118 | −30.801 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | 4 | 0.5000 | 0.7500 | −178.03 | 33.527 | −68.496 | 28.943 | 0.9271 | 13.279 | −11.171 | −25.342 |
| 600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891 | aud1_clips/quiet.wav | quiet.wav | tone | 0 | 0 | 0.2500 | −539.46 | 67.211 | 49.211 | 33.436 | 20.060 | 1.288 | −12.820 | −5.981 |
| 600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891 | aud1_clips/quiet.wav | quiet.wav | tone | 1 | 0.1250 | 0.3750 | −539.46 | 67.211 | 49.211 | 33.436 | 20.060 | 1.288 | −12.820 | −5.981 |
| 600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891 | aud1_clips/quiet.wav | quiet.wav | tone | 2 | 0.2500 | 0.5000 | −539.46 | 67.211 | 49.211 | 33.436 | 20.060 | 1.288 | −12.820 | −5.981 |
| 399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84 | aud1_clips/silence.wav | silence.wav | silence | 0 | 0 | 0.2500 | −632.46 | 1.332e-15 | 6.795e-14 | −5.773e-14 | 4.663e-14 | −9.437e-14 | 3.908e-14 | 4.519e-14 |
| 399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84 | aud1_clips/silence.wav | silence.wav | silence | 1 | 0.1250 | 0.3750 | −632.46 | 1.332e-15 | 6.795e-14 | −5.773e-14 | 4.663e-14 | −9.437e-14 | 3.908e-14 | 4.519e-14 |
| 399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84 | aud1_clips/silence.wav | silence.wav | silence | 2 | 0.2500 | 0.5000 | −632.46 | 1.332e-15 | 6.795e-14 | −5.773e-14 | 4.663e-14 | −9.437e-14 | 3.908e-14 | 4.519e-14 |
| 4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485 | aud1_clips/speechlike.wav | speechlike.wav | speech | 0 | 0 | 0.2500 | −250.01 | 52.384 | 35.005 | 15.503 | 3.993 | 4.156 | 9.339 | 7.542 |
| 4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485 | aud1_clips/speechlike.wav | speechlike.wav | speech | 1 | 0.1250 | 0.3750 | −279.49 | 14.341 | 9.378 | 4.361 | 1.542 | 1.468 | 2.960 | 0.4343 |
| 4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485 | aud1_clips/speechlike.wav | speechlike.wav | speech | 2 | 0.2500 | 0.5000 | −296.28 | −2.425 | 0.4222 | −0.0550 | 0.2115 | 0.2390 | 0.3478 | −1.327 |
Files that could not be read
| File | Path |
|---|---|
| notes.wav | aud1_clips/notes.wav |
| not_there.wav | aud1_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"))
))
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_id | path | file | label | window | start_s | end_s | mfcc_1_mean | mfcc_2_mean | mfcc_3_mean | mfcc_4_mean | mfcc_5_mean | mfcc_6_mean | mfcc_7_mean | mfcc_8_mean |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | 0 | 0 | 0.2500 | −374.18 | 25.425 | 6.214 | 2.943 | −1.579 | −4.190 | −5.939 | −6.115 |
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | 1 | 0.1250 | 0.3750 | −354.30 | 52.899 | 27.581 | 11.378 | −6.144 | −19.507 | −27.644 | −29.338 |
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | 2 | 0.2500 | 0.5000 | −340.84 | 68.267 | 38.612 | 16.048 | −8.544 | −28.089 | −40.126 | −42.751 |
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | 3 | 0.3750 | 0.6250 | −340.84 | 68.267 | 38.612 | 16.048 | −8.544 | −28.089 | −40.126 | −42.751 |
| dab1d1236691977bcf1a4702c69b2fe276e83f28554009346c0251cc51902943 | aud1_clips/tone_a.wav | tone_a.wav | tone | 4 | 0.5000 | 0.7500 | −340.84 | 68.267 | 38.612 | 16.048 | −8.544 | −28.089 | −40.126 | −42.751 |
| 2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920 | aud1_clips/tone_b.wav | tone_b.wav | tone | 0 | 0 | 0.2500 | −222.07 | 29.941 | 8.669 | −11.999 | −25.920 | −26.574 | −17.573 | −0.7668 |
| 2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920 | aud1_clips/tone_b.wav | tone_b.wav | tone | 1 | 0.1250 | 0.3750 | −222.28 | 31.290 | 8.134 | −12.813 | −25.031 | −26.440 | −16.481 | −0.7517 |
| 2cb71df8556b503057ec5f6bf604895994a85268eab9dc203e634dadc6012920 | aud1_clips/tone_b.wav | tone_b.wav | tone | 2 | 0.2500 | 0.5000 | −221.45 | 31.661 | 8.083 | −12.736 | −24.491 | −26.227 | −18.009 | −1.489 |
| 0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5 | aud1_clips/noise_a.wav | noise_a.wav | noise | 0 | 0 | 0.2500 | −209.09 | 134.19 | −25.516 | −1.882 | −5.504 | 10.794 | −4.098 | −1.386 |
| 0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5 | aud1_clips/noise_a.wav | noise_a.wav | noise | 1 | 0.1250 | 0.3750 | −210.13 | 137.05 | −26.998 | −1.242 | −7.145 | 11.999 | −4.515 | −0.9428 |
| 0fdd11a9c2f3ba6dbd47e153e0515a2cfe6090efe2e242b8bdbbed5590d84ed5 | aud1_clips/noise_a.wav | noise_a.wav | noise | 2 | 0.2500 | 0.5000 | −207.62 | 135.70 | −26.970 | −2.164 | −6.490 | 10.815 | −4.026 | −1.048 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | 0 | 0 | 0.2500 | −161.48 | 77.449 | −31.644 | 27.305 | −20.296 | −19.750 | −13.687 | −22.613 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | 1 | 0.1250 | 0.3750 | −163.32 | 61.347 | −47.660 | 9.464 | −39.690 | −26.262 | 5.831 | −0.5483 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | 2 | 0.2500 | 0.5000 | −162.24 | 53.893 | −58.770 | 1.635 | −36.126 | 13.402 | 31.016 | −5.582 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | 3 | 0.3750 | 0.6250 | −162.65 | 45.275 | −62.822 | 8.682 | −12.657 | 33.939 | 4.118 | −30.801 |
| 07ed44d27e05267dd00a2c0a2f887d1974dae586e28a90b13ed183a8882ed402 | aud1_clips/chirp_loud.wav | chirp_loud.wav | chirp | 4 | 0.5000 | 0.7500 | −178.03 | 33.527 | −68.496 | 28.943 | 0.9271 | 13.279 | −11.171 | −25.342 |
| 600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891 | aud1_clips/quiet.wav | quiet.wav | tone | 0 | 0 | 0.2500 | −539.46 | 67.211 | 49.211 | 33.436 | 20.060 | 1.288 | −12.820 | −5.981 |
| 600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891 | aud1_clips/quiet.wav | quiet.wav | tone | 1 | 0.1250 | 0.3750 | −539.46 | 67.211 | 49.211 | 33.436 | 20.060 | 1.288 | −12.820 | −5.981 |
| 600c187397f5f9d611f8311e65012590758b873d90813304cfefbad28507f891 | aud1_clips/quiet.wav | quiet.wav | tone | 2 | 0.2500 | 0.5000 | −539.46 | 67.211 | 49.211 | 33.436 | 20.060 | 1.288 | −12.820 | −5.981 |
| 399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84 | aud1_clips/silence.wav | silence.wav | silence | 0 | 0 | 0.2500 | −632.46 | 1.332e-15 | 6.795e-14 | −5.773e-14 | 4.663e-14 | −9.437e-14 | 3.908e-14 | 4.519e-14 |
| 399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84 | aud1_clips/silence.wav | silence.wav | silence | 1 | 0.1250 | 0.3750 | −632.46 | 1.332e-15 | 6.795e-14 | −5.773e-14 | 4.663e-14 | −9.437e-14 | 3.908e-14 | 4.519e-14 |
| 399af1c07fc24c231ea1f40223f625f759841d1c7c2120a767bc410f29753f84 | aud1_clips/silence.wav | silence.wav | silence | 2 | 0.2500 | 0.5000 | −632.46 | 1.332e-15 | 6.795e-14 | −5.773e-14 | 4.663e-14 | −9.437e-14 | 3.908e-14 | 4.519e-14 |
| 4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485 | aud1_clips/speechlike.wav | speechlike.wav | speech | 0 | 0 | 0.2500 | −250.01 | 52.384 | 35.005 | 15.503 | 3.993 | 4.156 | 9.339 | 7.542 |
| 4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485 | aud1_clips/speechlike.wav | speechlike.wav | speech | 1 | 0.1250 | 0.3750 | −279.49 | 14.341 | 9.378 | 4.361 | 1.542 | 1.468 | 2.960 | 0.4343 |
| 4bffd8346c506f0b5d74a0ec425939f35fcf79c2c7315cd036450fbc903d6485 | aud1_clips/speechlike.wav | speechlike.wav | speech | 2 | 0.2500 | 0.5000 | −296.28 | −2.425 | 0.4222 | −0.0550 | 0.2115 | 0.2390 | 0.3478 | −1.327 |
Files that could not be read
| File | Path |
|---|---|
| notes.wav | aud1_clips/notes.wav |
| not_there.wav | aud1_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