ADescribe · audio.features
Audio features (MFCC, spectral shape, chroma, loudness)
Which numbers describe each audio file (or each second of it), so the usual methods can learn from them?
Turns each audio file into a row of numbers: MFCCs (the timbre of the sound), spectral centroid, bandwidth, rolloff and flatness (brightness and noisiness), chroma (the 12 pitch classes), RMS energy, zero-crossing rate and integrated loudness, each summarized over the file by its mean and spread. With windows on, every window of a file gets its own row. Save the table as a dataset to cluster, classify or check the files for anomalies with the methods you already use. Identical in Python and R.
A real result
Example “Files defaults”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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.
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.
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Files defaultsaud1_clips · audio: path · label: label
- All sets all statsaud1_clips · audio: path
- Windows mfcc onlyaud1_clips · audio: path · label: label
- Degenerate all naaud1_clips · audio: path
- Degenerate empty after filteraud1_clips · audio: path · label: label
- Degenerate n1aud1_clips · audio: path · label: label
- Degenerate n2aud1_clips · audio: path · label: label
- Degenerate n3aud1_clips · audio: path · label: label
In the guides
Where it sits in the decision guides
- Sequences, curves and signals (hidden Markov models, functional PCA, scattering) · DS & ML Decision Guide · Discover — find structure without labels
- Feature engineering: dates, interactions, splines, binning, text features · DS & ML Decision Guide · Prepare data for modelling
What you need
- Audio filecategorical · 1 column
- A column of audio file paths (an audio folder added in Data has one).
- Keep columncategorical · 0–1 column
- Optional: a column such as the class or speaker, copied into the feature table and used to color the map.
Choices you make
statistics
- MFCCsdefault on
Mel-frequency cepstral coefficients: the overall shape of the spectrum (timbre); the standard input for speech and sound classifiers.
- Spectral shapedefault on
Centroid (brightness), bandwidth (spread), rolloff (where 85% of the energy lies below) and flatness (noise-like vs tonal).
- Chromadefault off
Energy in each of the 12 pitch classes (C to B), useful for music; tuning is taken as standard (A = 440 Hz).
- Energy and zero crossingsdefault on
RMS level and the zero-crossing rate per frame (high for noisy or hissing sounds).
- Integrated loudnessdefault on
One BS.1770 loudness value (LUFS) per file or window; missing for silence or less than 0.4 s.
- Summariesdefault mean_sd
How each frame feature is summarized over a file or window.
- Mean and SD(default) — The average and the spread (population standard deviation) over frames.
- Mean only — Half as many columns; loses how much the sound changes.
- Mean, SD, min and max — Adds the extremes over frames.
- Number of MFCCsdefault 13
13 is the speech standard; more coefficients keep finer spectral detail. At most the number of mel bands.
Advanced
- Mel bandsdefault 40
Triangular mel filters the MFCCs are computed from.
- Sample rate (Hz)default 16000
Files are resampled to this rate first; 16 kHz is the speech standard, 22,050 or 44,100 Hz keeps more of music.
- Frame length (samples)default 512
Samples per analysis frame (Hann window); 512 at 16 kHz is 32 ms.
- Frame step (samples)default 160
Samples between frame starts; 160 at 16 kHz is 10 ms.
options
- One row per windowdefault off
Cut each file into windows and describe every window, for example to find the noisy seconds of a long recording.
- Window length (s)default 1
Length of each window when one row per window is on.
- Window step (s)default 0.5
Time between window starts; smaller than the length makes windows overlap.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Files decode
Files that can't be decoded or are missing are listed and left out.
One sample rate
Every file is resampled to the same rate first, so features compare across files recorded at different rates.
Summaries lose order
Means and SDs over a file ignore when things happen; use windows to keep time.
What it reports
- n_rows
- One row per file (or per window) with a column per summarized feature, saved as a dataset for clustering, learners or anomaly checks.
- n_files
- One row per file (or per window) with a column per summarized feature, saved as a dataset for clustering, learners or anomaly checks.
- n_unreadable
- One row per file (or per window) with a column per summarized feature, saved as a dataset for clustering, learners or anomaly checks.
- n_out_rows
- One row per file (or per window) with a column per summarized feature, saved as a dataset for clustering, learners or anomaly checks.
- n_features
- One row per file (or per window) with a column per summarized feature, saved as a dataset for clustering, learners or anomaly checks.
- sample_rate
- How 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.
- frame_ms
- A sound cut into short overlapping windowed frames, each turned into frequencies: the basis of spectrograms and most audio features.
- hop_ms
- A sound cut into short overlapping windowed frames, each turned into frequencies: the basis of spectrograms and most audio features.
Per group, level or term: mean[<feature>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses numpy, pandas, scipy, codesplash; R uses nanoparquet, jsonlite, codesplashr.
Default traps between the two languages
- Both engines read the same decoded samples and run the same twins (codesplash.audio.features / dsp ↔ codesplashr R/audio_features.R / R/audio_dsp.R); FFTs (pocketfft ↔ R's fft) and the loudness filter differ only in rounding.
The exact script CodeSplash ran for example “Files defaults” · 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"}],
})
The exact script CodeSplash ran for example “Files defaults” · 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"))
))
Sources
- Davis S, Mermelstein P (1980). Comparison of parametric representations for monosyllabic word recognition in continuously spoken sentences. IEEE TASSP 28(4):357–366.
- Slaney M (1998). Auditory Toolbox, version 2. Interval Research Corporation technical report 1998-010.
- McFee B, Raffel C, Liang D, et al. (2015). librosa: audio and music signal analysis in Python. SciPy 2015, 18–25.
- Ellis DPW (2007). Chroma feature analysis and synthesis. LabROSA, Columbia University.
- ITU-R Recommendation BS.1770-4 (2015). Algorithms to measure audio programme loudness and true-peak audio level.
From the CodeSplash method registry · audio.features v1.0.0.