Moving from librosa
This page is for someone who knows librosa and is deciding
whether to switch to audio_samples. It gives measurements on both sides, a pipeline
written in both libraries, the differences that catch people out, recipes for common
jobs, a way to migrate in steps, and the cases where librosa is still the better choice.
Coming from librosa is the function-by-function lookup. Rust users and anyone porting
a pipeline to Rust should also read
the Rust companion.
audio_samples is not a wrapper around librosa or a copy of it. It is a Rust library
with Python bindings. Its librosa-compatible layer reproduces librosa 1.0 results where
that makes sense and departs from librosa’s defaults where those change the data
without being asked.
Install it from source
Important
The API on this page is not in a PyPI release. pip install audio_samples gives
version 0.2.4, which has no stft_matrix, mfcc_frames, spectral,
features, rhythm, effects or sequence. That release has one wheel,
CPython 3.12 on x86-64 Linux; on anything else pip tries to build the source
distribution, which needs a Rust toolchain. Until 0.3.0, which includes it, is on PyPI, build
from two checkouts side by side that contain it. The steps below were tested with
rustc 1.96.0:
git clone https://github.com/jmg049/audio_samples
git clone https://github.com/jmg049/audio_samples_python
cd audio_samples_python
python -m venv .venv && source .venv/bin/activate
pip install maturin
maturin develop --release
The bindings have one required Python dependency, NumPy. Every example below has run only on x86-64 Linux, on CPython 3.13.
Evidence
Every comparison below gives both libraries’ numbers: “ours” is audio_samples, “librosa” is
librosa. All of it was measured on 2026-11-04 on one machine, so treat absolute times as that
machine’s, and the ratios as what to expect, not as a promise for yours. A ratio is ours divided by
librosa: below 1 means ours is faster or smaller.
Machine |
Intel i7-13700KF, Linux 7.2.0-1-cachyos, x86-64 |
librosa side |
librosa 1.0.0, CPython 3.13.11, NumPy 2.5.3, SciPy 1.18.1, soxr 1.1.0, soundfile 0.14.0 (libsndfile 1.2.2), numba 0.68.0 |
Our side |
|
Method. Each case calls one librosa function and its equivalent on the same samples. Single-core runs are pinned to one performance core with every thread count set to 1; each row is the median of repeated calls after warm-up, at least 0.3 s and 5 calls. Rows within 3 % are timed again in one process with the two libraries alternating, so that they share clock and cache state. Memory is the peak allocated per call under memray, counting NumPy and Rust alike, and the exact peak resident growth per call in fresh processes. “Native” is the Rust library called directly.
What depends on matched settings. Every row calls both libraries with librosa 1.0’s settings,
passing them explicitly where this library’s default differs (see changed defaults). So a row
compares the same work; it does not compare the two default calls. Where those differ in work
(mfcc_frames() without an 80 dB floor, io.read that does not resample) the table says so.
Reproduce it from the two checkouts, with librosa, memray and the bindings in the bindings’ virtual environment:
cd audio_samples
OUT=/path/to/results
R=benches/librosa_compare/run.sh
$R $OUT build signals
for g in spectrum features tonal constant_q pitch effects rhythm sequence convert; do
SEL="--groups $g" $R $OUT rust py mem
done
$R $OUT default
JOBS=6 REPEATS=5 $R $OUT rss
$R $OUT report ties report load startup guide
Whole benchmark
Every librosa function with an equivalent here: 176 cases and 1157 rows, several inputs each (1, 10 and 60 s, 16000 and 22050 Hz, float32 and float64, mono and stereo).
Measure |
Rows |
Ours lower |
Equal |
Ours higher |
|---|---|---|---|---|
Time through Python, one core |
1157 |
1157 |
0 |
0 |
Time, native Rust, one core |
1157 |
1157 |
0 |
0 |
Time through Python, default threading |
326 |
326 |
0 |
0 |
Time, native Rust, default threading |
326 |
326 |
0 |
0 |
Peak allocation per call through Python |
1157 |
1123 |
34 |
0 |
Peak allocation per call, native |
1157 |
1123 |
34 |
0 |
Peak resident growth per call |
461 |
437 |
24 |
0 |
Over all rows: median time ratio 0.30 (90th percentile 0.64, worst 0.995), median memory ratio 0.38 (worst 1.00). “Equal” rows allocate the same single array on both sides (a matrix, a view of the input, a table from NumPy’s small-block cache), so there is nothing left to take out. The ratios by area, ours / librosa, one core:
Area |
Rows |
Time, median |
Time, worst |
Native time, median |
Memory, median |
Memory, worst |
|---|---|---|---|---|---|---|
STFT, dB, mel, MFCC, windows |
113 |
0.40 |
1.00 |
0.39 |
0.53 |
1.00 |
Spectral features |
166 |
0.32 |
0.86 |
0.31 |
0.22 |
0.67 |
Chroma, tuning |
56 |
0.26 |
0.80 |
0.26 |
0.41 |
0.42 |
Constant-Q |
143 |
0.30 |
0.86 |
0.30 |
0.42 |
0.94 |
YIN, pYIN, harmonics |
36 |
0.24 |
0.65 |
0.24 |
0.12 |
0.92 |
Onsets, tempo, beats |
190 |
0.27 |
0.86 |
0.27 |
0.32 |
0.87 |
Effects, HPSS, resampling |
356 |
0.40 |
0.96 |
0.41 |
0.50 |
1.00 |
DTW, Viterbi, recurrence |
70 |
0.10 |
0.96 |
0.09 |
0.60 |
1.00 |
Unit conversions |
27 |
0.29 |
0.73 |
0.31 |
0.50 |
1.00 |
All rows |
1157 |
0.30 |
1.00 |
0.30 |
0.38 |
1.00 |
Common functions on 10 s of mono float32 at 22050 Hz, one core:
Function |
Ours, Python ms |
Ours, native ms |
librosa ms |
Time ratio |
Ours peak |
librosa peak |
|---|---|---|---|---|---|---|
|
1.04 |
0.992 |
3.1 |
0.33 |
3.5 MB |
4.5 MB |
|
1.05 |
1.19 |
5.57 |
0.19 |
2.6 MB |
4.9 MB |
|
1.12 |
1.13 |
4.48 |
0.25 |
1.9 MB |
5.1 MB |
|
1.25 |
1.25 |
4.69 |
0.27 |
1.9 MB |
5.1 MB |
|
2.76 |
2.59 |
9.97 |
0.28 |
5.1 MB |
12.3 MB |
|
11.3 |
11.7 |
33.6 |
0.34 |
5.1 MB |
12.3 MB |
|
1.71 |
1.7 |
9.7 |
0.18 |
786 KB |
1.9 MB |
|
1.18 |
1.19 |
4.72 |
0.25 |
1.8 MB |
10.2 MB |
|
0.171 |
0.168 |
0.307 |
0.56 |
138 KB |
4.2 MB |
|
0.127 |
0.127 |
2.82 |
0.04 |
22 KB |
1.8 MB |
|
1.22 |
1.22 |
5.39 |
0.23 |
1.9 MB |
5.1 MB |
|
1.89 |
1.9 |
7.34 |
0.26 |
1.9 MB |
7.1 MB |
|
2.45 |
2.46 |
7.36 |
0.33 |
1.9 MB |
7.1 MB |
|
3.39 |
3.38 |
10.6 |
0.32 |
1.1 MB |
17.8 MB |
|
75.2 |
68.2 |
127 |
0.59 |
22.1 MB |
40.2 MB |
|
153 |
154 |
245 |
0.63 |
15.2 MB |
25.7 MB |
|
6.51 |
6.68 |
13.3 |
0.49 |
11.8 MB |
20.2 MB |
|
9.48 |
9.79 |
21.4 |
0.44 |
12.5 MB |
28.0 MB |
|
111 |
105 |
352 |
0.32 |
11.1 MB |
15.0 MB |
|
0.186 |
0.205 |
0.305 |
0.61 |
784 KB |
4.2 MB |
|
0.634 |
0.648 |
1.47 |
0.43 |
1.7 MB |
5.1 MB |
|
0.792 |
0.801 |
3.08 |
0.26 |
2.5 MB |
4.1 MB |
|
2.14 |
2.33 |
11.4 |
0.19 |
880 KB |
2.8 MB |
|
0.82 |
0.811 |
42.7 |
0.02 |
207 KB |
547 KB |
The weakest rows by time. They are functions where both sides do one allocation and a copy, or the resampler at float64:
Case |
Input |
Ours ms |
librosa ms |
Ratio |
|---|---|---|---|---|
|
vec_f64 |
0.009412 |
0.009456 |
0.995 |
|
16000_60s_mono_f64 |
0.2211 |
0.2298 |
0.962 |
|
const_f64 |
0.1567 |
0.1635 |
0.958 |
|
22050_60s_mono_f64 |
0.3057 |
0.3197 |
0.956 |
|
22050_60s_mono_f32 |
0.1525 |
0.1598 |
0.954 |
|
16000_60s_mono_f64 |
6.439 |
6.77 |
0.951 |
|
16000_10s_mono_f64 |
1.071 |
1.129 |
0.948 |
|
16000_60s_mono_f32 |
0.1111 |
0.118 |
0.941 |
|
22050_10s_mono_f64 |
0.3868 |
0.4137 |
0.935 |
|
22050_10s_stereo_f64 |
0.7762 |
0.8433 |
0.920 |
Reading files
librosa.load and librosa.stream against the read path, with the same work on both sides. One
core; read and load stand for aus.io.read and librosa.load:
Work (60 s, stereo, 16-bit, 44100 Hz) |
File |
Ours ms |
librosa ms |
Ratio |
Ours peak |
librosa peak |
|---|---|---|---|---|---|---|
Whole file as float32 |
WAV |
3.14 |
6.82 |
0.46 |
20.2 MB |
20.2 MB |
Whole file as float32 |
FLAC |
29.9 |
33.5 |
0.89 |
20.3 MB |
20.3 MB |
Whole file as int16 |
WAV |
0.371 |
0.507 |
0.73 |
10.1 MB |
10.1 MB |
Whole file as int16 |
FLAC |
29.2 |
33.4 |
0.87 |
10.2 MB |
10.2 MB |
Mono float32 |
WAV |
6.47 |
38.8 |
0.17 |
30.3 MB |
40.5 MB |
Mono float32 |
FLAC |
31.3 |
65.3 |
0.48 |
30.3 MB |
40.5 MB |
Mono float32 at 22050 Hz |
WAV |
8.9 |
43.3 |
0.21 |
30.3 MB |
40.5 MB |
Mono float32 at 22050 Hz |
FLAC |
35.2 |
70.6 |
0.50 |
30.3 MB |
40.5 MB |
Stereo float32 at 22050 Hz |
WAV |
12.5 |
25.3 |
0.50 |
40.4 MB |
51.1 MB |
Stereo float32 at 22050 Hz |
FLAC |
35.8 |
52.9 |
0.68 |
30.3 MB |
51.1 MB |
2 s from 5 s in |
WAV |
0.0788 |
0.23 |
0.34 |
697 KB |
700 KB |
2 s from 5 s in |
FLAC |
1.08 |
1.34 |
0.81 |
794 KB |
1.3 MB |
Stream, overlapping blocks |
WAV |
2.76 |
10.1 |
0.27 |
2.0 MB |
7.0 MB |
Stream, overlapping blocks |
FLAC |
30.1 |
41.6 |
0.73 |
2.1 MB |
7.6 MB |
Stream, 4096 frames |
WAV |
3.11 |
11.3 |
0.28 |
72 KB |
236 KB |
Stream, 4096 frames |
FLAC |
30 |
40.1 |
0.75 |
152 KB |
828 KB |
Save, against |
WAV |
1.24 |
1.3 |
0.96 |
0 KB |
9 KB |
Save, against |
FLAC |
30.2 |
46.7 |
0.65 |
24.2 MB |
437 KB |
Over all 92 rows (WAV 16-bit, 24-bit and float; FLAC 16-bit and 24-bit; 10, 60 and 600 s; also float64,
header-only, mono streams and saves against soundfile.write): time 91 lower, 1 higher; peak allocation 88 lower, 0 equal, 4 higher; peak resident growth 35 lower, 2 equal, 1 higher. Each library’s plain default is different work: on the
60 s WAV aus.io.read(p) returns the 16-bit stereo samples, and librosa.load(p) also mixes down,
converts and resamples.
WAV against other readers and writers, with 48 combinations of type (int16, int32, float32), channels and length (1 to 600 s), the libraries alternating in one process. This is the harness of the article Working with WAV files. Files are on tmpfs, so this measures the libraries, not a disk. Peak allocation is lower or equal on 302 of 304 rows.
Against |
Operation |
Rows |
Ours slower |
Median ratio |
Worst ratio |
|---|---|---|---|---|---|
|
read |
48 |
5 |
0.90 |
1.187 |
|
read |
48 |
2 |
0.93 |
1.093 |
|
write |
48 |
6 |
0.86 |
1.040 |
|
read |
48 |
10 |
0.97 |
1.189 |
|
write |
48 |
17 |
0.98 |
1.041 |
|
read |
32 |
4 |
0.97 |
1.147 |
|
write |
32 |
9 |
0.98 |
1.046 |
Rows above 1 are bound by the copy between the kernel and user memory, and the spread of one such row over repeated calls is larger than the difference between the libraries.
Start-up
librosa loads its submodules on first use, then compiles numba functions and imports SciPy and scikit-learn. So its import is short and its first call is long. Fresh processes, one core:
|
Median ms (range), 30 fresh processes |
|---|---|
|
7.8 (7.4-8.5) |
|
10.1 (9.3-12.0) |
|
14.5 (13.7-15.3) |
|
44.8 (42.7-49.0) |
|
47.9 (45.6-52.7) |
|
46.1 (43.4-54.5) |
|
306.8 (285.3-333.9) |
The first call in a fresh process, on 10 s of float32 at 22050 Hz, in milliseconds. Medians and ranges
of 7 processes. audio_samples has nothing to compile, so its first call is close to its third:
Function |
Ours, first call |
Ours, third call |
librosa, first call |
librosa, third call |
|---|---|---|---|---|
|
2.1 (1.7-2.8) |
1.05 |
444.4 (441.2-448.0) |
2.9 |
|
2.2 (2.1-2.5) |
1.29 |
452.7 (449.3-460.0) |
5.31 |
|
3.5 (3.4-3.5) |
2.79 |
552.9 (531.3-644.0) |
10.3 |
|
2.0 (2.0-2.1) |
1.75 |
538.6 (534.1-552.0) |
9.74 |
|
2.1 (2.0-2.1) |
1.24 |
505.1 (501.2-524.7) |
5.07 |
|
3.4 (3.4-3.5) |
2.48 |
984.7 (970.1-1014.0) |
9.4 |
|
3.5 (3.5-3.6) |
3.36 |
291.9 (290.4-294.6) |
13 |
|
79.3 (76.6-85.1) |
77.7 |
673.1 (672.2-683.7) |
138 |
|
164.9 (163.1-166.2) |
162 |
766.5 (760.1-781.6) |
256 |
|
10.4 (9.5-11.2) |
9.29 |
552.7 (539.4-566.3) |
17.6 |
|
1.2 (1.2-1.3) |
0.63 |
167.4 (165.3-180.7) |
1.06 |
|
4.4 (4.3-4.4) |
4.08 |
566.1 (552.8-576.2) |
10.9 |
|
0.3 (0.3-0.3) |
0.233 |
257.4 (253.3-260.0) |
0.727 |
|
0.1 (0.1-0.1) |
0.0248 |
232.1 (223.1-237.0) |
0.057 |
|
0.4 (0.4-0.4) |
0.357 |
574.0 (566.0-584.7) |
20 |
The whole process, from start to exit: import, read the file, compute MFCCs with librosa’s settings. Medians and ranges of 30 processes, one core:
File (stereo, 44100 Hz) |
Settings |
Ours ms (range) |
librosa ms (range) |
|---|---|---|---|
16-bit WAV, 10s |
mono, 22050 Hz |
48.0 (46.8-49.7) |
572.2 (563.1-600.5) |
16-bit WAV, 10s |
mono, 44100 Hz |
49.0 (47.1-50.8) |
574.9 (564.8-603.6) |
16-bit WAV, 60s |
mono, 22050 Hz |
64.4 (62.7-68.4) |
627.5 (610.4-661.1) |
16-bit WAV, 60s |
mono, 44100 Hz |
71.6 (69.4-76.9) |
650.2 (633.3-748.7) |
16-bit FLAC, 60s |
mono, 22050 Hz |
88.6 (86.8-99.3) |
631.9 (618.9-736.1) |
16-bit FLAC, 60s |
mono, 44100 Hz |
96.1 (93.7-108.2) |
653.6 (642.2-774.2) |
Threads
MFCCs of a directory, each library’s own default threading, in milliseconds for all files (see Batch processing a directory, with threads):
16 files of 60 s |
Library |
1 thread |
2 threads |
4 threads |
8 threads |
16 threads |
|---|---|---|---|---|---|---|
WAV |
librosa |
1138 |
632 |
436 |
354 |
296 |
WAV |
ours |
272 |
161 |
112 |
99 |
102 |
FLAC |
librosa |
1642 |
916 |
541 |
370 |
357 |
FLAC |
ours |
724 |
388 |
213 |
135 |
119 |
Install
See the table under When to stay on librosa: the compiled wheel is larger than librosa’s own, and the whole environment is smaller.
Agreement with librosa
See Getting librosa’s exact results. In short: given the same samples, most results agree to round-off of the type in use and discrete results (onset and beat frames, tempo, paths) are identical; anything that goes through soxr agrees less closely.
A complete pipeline, side by side
Every Python block on this page runs, in order, in the test suite
(tests/test_moving_from_librosa.py), and the assert lines are the comparison: if
a result stopped matching, the test would fail. The first block writes the file the rest
use: 20 s of decaying notes at 120 BPM, stereo, 44100 Hz, float32 WAV.
import numpy as np
import audio_samples as aus
sr_file = 44100
n = 20 * sr_file
noise = np.random.default_rng(0).standard_normal((2, n))
x = 0.002 * noise
for k in range(40):
start, length = k * sr_file // 2, 2 * sr_file // 5
t = np.arange(length) / sr_file
f = 110.0 * 2.0 ** (((k * 7) % 24) / 12.0)
note = np.exp(-8.0 * t) * (0.5 * np.sin(2 * np.pi * f * t) + 0.25 * np.sin(4 * np.pi * f * t))
x[0, start : start + length] += note
x[1, start : start + length] += 0.8 * note
song = aus.AudioSamples.new_multi(x.astype(np.float32), sr_file)
aus.io.save("song.wav", song)
def relative_error(ours, theirs):
"""Largest difference as a fraction of the largest value."""
return np.abs(ours - theirs).max() / np.abs(theirs).max()
The pipeline in librosa:
import librosa
y, sr = librosa.load("song.wav") # mono, 22050 Hz, float32
D = librosa.stft(y)
S = librosa.feature.melspectrogram(y=y, sr=sr)
S_db = librosa.power_to_db(S, ref=np.max)
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)
onsets = librosa.onset.onset_detect(y=y, sr=sr, units="time")
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, units="time")
The same in audio_samples. Each thing librosa does by default is written out: the
type, the mix-down, the rate, the 80 dB floor and beat trimming.
a = (
aus.io.read("song.wav", as_type=aus.SampleType.F32)
.to_mono()
.resample(22050, "high")
)
a_D = a.stft_matrix() # (channels, bins, frames)
a_S = a.melspectrogram()
a_S_db = aus.spectral.power_to_db(a_S, ref=np.max, top_db=80.0)
a_mfcc = a.mfcc_frames(n_mfcc=13, top_db=80.0)
a_onsets = a.onset_detect(units="time")
a_tempo, a_beats = a.beat_track(units="time", trim=True)
The shapes differ by the leading channel axis. Onsets, tempo and beats are identical on this file. The resamplers are different algorithms (see Resampling is not soxr), which is where the differences in the arrays come from:
assert a.to_numpy().dtype == y.dtype == np.float32
assert a.sample_rate == sr == 22050
assert a_D.shape == (1, *D.shape) and a_mfcc.shape == (1, *mfcc.shape)
# The two resamplers: about 95 dB apart here.
snr_db = 10 * np.log10(np.sum(y**2) / np.sum((a.to_numpy() - y) ** 2))
assert snr_db > 90
assert relative_error(a_D[0], D) < 2e-5
assert relative_error(a_S[0], S) < 2e-6
assert relative_error(a_mfcc[0], mfcc) < 2e-4
assert np.array_equal(a_onsets, onsets)
assert a_tempo[0] == tempo[0]
assert np.array_equal(a_beats, beats)
Feed both libraries the same samples and the resampler is out of the comparison. The rest then agrees to float32 round-off, and to about 1e-15 in float64 when librosa is told to build its mel basis in float64:
b = aus.AudioSamples.new_mono(y, sr)
assert relative_error(b.stft_matrix()[0], D) < 1e-6
assert relative_error(b.melspectrogram()[0], S) < 1e-6
assert relative_error(b.mfcc_frames(n_mfcc=13, top_db=80.0)[0], mfcc) < 5e-6
y64 = y.astype(np.float64)
b64 = aus.AudioSamples.new_mono(y64, sr)
S64 = librosa.feature.melspectrogram(y=y64, sr=sr, dtype=np.float64)
assert relative_error(b64.melspectrogram()[0], S64) < 1e-14
mfcc64 = librosa.feature.mfcc(y=y64, sr=sr, dtype=np.float64)
assert relative_error(b64.mfcc_frames(top_db=80.0)[0], mfcc64) < 1e-13
The differences that will trip you up
Each item shows the librosa code, what a direct translation does, and the correct form.
raises below returns the error message, and fails if nothing is raised.
def raises(exception, call):
try:
call()
except exception as error:
return str(error)
raise AssertionError("nothing was raised")
The audio carries its rate
librosa passes y and sr around. Here the audio holds its rate, and methods have
neither argument. Passing either is a TypeError, not something ignored:
# librosa.feature.melspectrogram(y=y, sr=sr)
assert "unexpected keyword argument 'sr'" in raises(TypeError, lambda: b.melspectrogram(sr=sr))
assert "unexpected keyword argument 'y'" in raises(TypeError, lambda: b.melspectrogram(y=y))
# librosa.effects.pitch_shift(y, sr=sr, n_steps=2)
up = b.pitch_shift(2.0)
assert up.sample_rate == sr
Free functions over arrays do take sr, and it is required where librosa defaults it
to 22050. A wrong default rate gives wrong results with no error, so there is no default:
# librosa.onset.onset_strength(S=S_db, sr=sr)
env = aus.rhythm.onset_strength(S=S_db, sr=sr)
assert raises(TypeError, lambda: aus.rhythm.onset_strength(S=S_db))
assert relative_error(env, librosa.onset.onset_strength(S=S_db, sr=sr)) < 1e-5
Some unit conversions in utils take it positionally under another name.
utils.frames_to_time takes (frames, sample_rate, hop_size):
# librosa.frames_to_time(10, sr=22050, hop_length=512)
assert aus.utils.frames_to_time(10, 22050, 512) == librosa.frames_to_time(10, sr=22050, hop_length=512)
Reading a file changes nothing
librosa.load(path) returns mono float32 at 22050 Hz whatever the file holds.
aus.io.read(path) returns what the file holds: rate, channels and sample type. Code
that assumes librosa’s result keeps running on different data, so check this first when
porting.
aus.io.save("song16.wav", song, as_type=aus.SampleType.I16)
y16, sr16 = librosa.load("song16.wav")
assert (y16.dtype, y16.ndim, sr16) == (np.float32, 1, 22050)
naive = aus.io.read("song16.wav") # the direct translation
assert naive.to_numpy().dtype == np.int16
assert naive.num_channels == 2 and naive.sample_rate == 44100
# What librosa.load(path) did:
same = aus.io.read("song16.wav", as_type=aus.SampleType.F32).to_mono().resample(22050, "high")
assert same.to_numpy().dtype == np.float32 and same.sample_rate == 22050
16-bit values are raw integers until you ask for floats. Analysis methods convert them
themselves, so this is only a trap if you take the array out. The scaling is also not
quite librosa’s: negative values are divided by 32768 and positive ones by 32767, where
libsndfile divides both by 32768, so a 16-bit file read as float differs from
librosa.load(path, sr=None) by at most about 3e-5:
ours16 = aus.io.read("song16.wav", as_type=aus.SampleType.F32).to_numpy()
theirs16, _ = librosa.load("song16.wav", sr=None, mono=False)
assert 0 < np.abs(ours16 - theirs16).max() < 3.1e-5
Precision follows the input
Analysis of uint8, int16, int24 and float32 audio returns float32 or
complex64; int32 and float64 audio returns float64 or complex128.
Audio-returning operations keep the sample type. librosa’s float32 input stays float32 for
most results, but it also promotes some (yin, pyin, tempogram) and it builds
mel and chroma bases in float32 even for float64 input.
assert naive.mfcc_frames().dtype == np.float32 # int16 audio
assert naive.time_stretch(2.0).to_numpy().dtype == np.int16 # stays int16
assert b64.stft_matrix().dtype == np.complex128
f0_ours = b.yin(fmin=65.4, fmax=2093.0)
f0_theirs = librosa.yin(y, fmin=65.4, fmax=2093.0, sr=sr)
assert f0_ours.dtype == np.float32 and f0_theirs.dtype == np.float64
Free functions over arrays compute in float32 for a float32 or complex64
array, and for float32 AudioSamples; everything else is converted to float64.
Integer arrays are converted by value, without audio scaling, so give them floats. Passing
dtype= to griffinlim is accepted and ignored: the input’s precision decides.
The type stubs state this rule, so mypy and pyright know the result’s dtype when they know the input’s.
AudioSamples is generic in its sample type: generation.sine_wave(440.0, 1.0, dtype=np.float64) is an
AudioSamples[np.float64], and its melspectrogram() is NDArray[np.float64]. The sample type of audio read
from a file is known only at run time, so io.read gives an AudioSamples of unknown sample type, whose results
have an unknown dtype. A file’s sample type can be stated with an annotation on the result of io.read.
Some defaults are different on purpose
Where librosa’s default changes the data without being asked, this library does not
follow it. These calls run without a complaint and give different numbers, so they are the
most important ones to check. In Rust, X::librosa() builds a config with librosa’s
settings; in Python there are no presets, so pass the keyword.
Argument |
librosa |
audio_samples, and what to pass |
|---|---|---|
|
80 |
|
|
-80 |
|
|
|
|
|
|
|
|
unseeded |
|
|
|
|
|
|
|
|
60 |
required |
|
22050, 512 |
required |
|
|
|
# librosa.power_to_db(S, ref=np.max) floors at -80 dB; the direct translation does not.
assert librosa.power_to_db(S, ref=np.max).min() == -80.0
assert aus.spectral.power_to_db(S, ref=np.max).min() < -80.0
assert aus.spectral.power_to_db(S, ref=np.max, top_db=80.0).min() == -80.0
# librosa.beat.beat_track keeps fewer beats than the direct translation.
assert len(b.beat_track(units="time")[1]) > len(beats)
assert np.array_equal(b.beat_track(units="time", trim=True)[1], beats)
# librosa.feature.chroma_stft estimates the tuning; the direct translation assumes 0.
chroma = librosa.feature.chroma_stft(y=y, sr=sr)
assert np.abs(b.chroma_stft()[0] - chroma).max() > 1e-3
assert np.abs(b.chroma_stft(tuning=None)[0] - chroma).max() < 1e-5
# librosa.hz_to_mel uses the Slaney scale; utils.hz_to_mel defaults to HTK.
assert aus.utils.hz_to_mel(440.0) != librosa.hz_to_mel(440.0)
assert aus.utils.hz_to_mel(440.0, htk=False) == librosa.hz_to_mel(440.0)
The onset envelope and spectral_contrast keep librosa’s 80 dB floor, which is part of
how those features are defined.
Boolean results
recurrence_matrix and cross_similarity in connectivity mode return bool, as in
librosa. viterbi_binary returns bool states where librosa returns uint16; ask
for librosa’s type if later code does arithmetic on the states.
features = np.random.default_rng(1).random((4, 30))
assert aus.sequence.recurrence_matrix(features).dtype == np.bool_
assert librosa.segment.recurrence_matrix(features).dtype == np.bool_
prob = np.random.default_rng(2).random((3, 30))
transition = np.array([[0.8, 0.2], [0.2, 0.8]])
states = librosa.sequence.viterbi_binary(prob, transition)
assert states.dtype == np.uint16
assert aus.sequence.viterbi_binary(prob, transition).dtype == np.bool_
assert np.array_equal(aus.sequence.viterbi_binary(prob, transition, dtype=np.uint16), states)
Shapes and channel layout
Methods always return a leading channel axis, also for mono: (channels, n_features,
n_frames), and (channels, n_frames) for onset envelopes and pitch tracks. librosa
drops the axis for 1-D input. Index [0] to get its mono shape. Free functions follow
librosa’s shapes.
assert b.melspectrogram().shape == (1, *S.shape)
assert b.onset_strength().shape[0] == 1
assert aus.spectral.stft(y).shape == D.shape
stereo = aus.io.read("song.wav")
assert stereo.shape == [2, n]
assert stereo.melspectrogram().shape[0] == 2
Some methods have the name you would reach for and do something else: they belong to the library’s own API, not to the librosa-compatible layer. The ones that take arguments fail loudly. These do not: they return one number for the whole signal.
assert isinstance(b.rms(), float) # use rms_frames()
assert isinstance(b.spectral_centroid(), float) # use spectral_centroid_frames()
assert isinstance(b.zero_crossing_rate(), float) # in Hz; use zero_crossing_rate_frames()
assert "params" in raises(TypeError, lambda: b.stft()) # use stft_matrix()
assert "mfcc_params" in raises(TypeError, lambda: b.mfcc()) # use mfcc_frames()
assert "config" in raises(TypeError, lambda: b.hpss()) # use harmonic_percussive()
raises(TypeError, lambda: b.trim()) # use trim_db(top_db=60.0)
Errors where librosa warns or carries on
# librosa returns n_mels rows; here it is an error.
assert librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40, n_mels=20).shape[0] == 20
assert "n_mfcc" in raises(ValueError, lambda: b.mfcc_frames(n_mfcc=40, n_mels=20))
# librosa detects onsets per channel only with sparse=False; here mono is required.
assert "mono" in raises(ValueError, lambda: stereo.onset_detect())
assert "sparse" in raises(ValueError, lambda: b.onset_detect(sparse=False))
# Options that are not implemented raise instead of being ignored.
assert "scale" in raises(ValueError, lambda: b.pitch_shift(2.0, scale=True))
# trim with a fixed reference when every frame is below it.
quiet = np.zeros(4096, dtype=np.float32)
assert librosa.effects.trim(quiet, top_db=60, ref=1.0)[0].size == 0
assert "silent" in raises(ValueError, lambda: aus.AudioSamples.new_mono(quiet, sr).trim_db(top_db=60.0, ref=1.0))
Resampling is not soxr
librosa.resample uses soxr. This library has its own delay-free Kaiser-windowed sinc
resampler. "high" is designed after soxr_hq’s passband and attenuation but does not
reproduce it, so anything downstream of resampling agrees less closely than everything
else on this page. Measured against librosa 1.0.0 (soxr 1.1.0) from 22050 Hz to 11025, 16000 and 44100 Hz: 129
to 135 dB SNR in the middle of a band-limited signal, 59 to 104 dB at its abrupt edges, 50
to 58 dB on white noise. "very_high" (what res_type="soxr_vhq" selects) has a passband
to 0.95 x Nyquist and a 185 dB stopband. There is no res_type choice of other filter designs
(kaiser_best, scipy and so on), and fractional rates are not accepted.
AudioSamples.resample defaults to "fast", which is a much lower quality:
ours_fast = b.resample(16000).to_numpy()
ours_high = b.resample(16000, "high").to_numpy()
theirs = librosa.resample(y, orig_sr=sr, target_sr=16000)
snr = lambda u, v: 10 * np.log10(np.sum(v**2) / np.sum((u - v) ** 2))
assert snr(ours_high, theirs) > 80 > snr(ours_fast, theirs)
assert b.resample(16000, "high").samples_per_channel() == int(np.ceil(y.size * 16000 / sr))
Everything that resamples inside inherits the difference: pitch_shift, cqt,
vqt, hybrid_cqt, chroma_cqt, chroma_cens, tonnetz, icqt.
Keyword names
Parameter names follow librosa 1.0 in the librosa-compatible layer, with these exceptions.
Some method names differ because the plain name was taken: stft_matrix, mfcc_frames,
spectral_centroid_frames and the other _frames features, trim_db, split_db,
harmonic_percussive. The weightings are lower case (features.a_weighting). Unit
conversions: hz_to_note is utils.frequency_to_note and returns (name, cents);
note_to_hz is utils.note_to_frequency; time_to_frames is
utils.time_to_frames_floor, because utils.time_to_frames rounds to nearest. Sharps
are ASCII #.
assert aus.utils.frequency_to_note(440.0)[0] == librosa.hz_to_note(440.0, unicode=False)
assert aus.utils.note_to_frequency("A4") == librosa.note_to_hz("A4")
times = [0.1, 0.7, 1.3]
assert np.array_equal(
aus.utils.time_to_frames_floor(times, sr=22050, hop_length=512),
librosa.time_to_frames(times, sr=22050, hop_length=512),
)
Getting librosa’s exact results
Pass librosa’s value for each default in changed defaults, feed both libraries the same
samples, and compare in the precision you care about. Rust configs have X::librosa()
for this; the Python bindings have no presets. This is what agrees and how closely, from the
golden suite (fixtures generated by librosa 1.0.0; cargo test --release --features
full_no_plotting --test analysis_reference -- --nocapture), in float64, as a fraction of
the peak:
Area |
Worst measured |
Notes |
|---|---|---|
Windows, mel and chroma filterbanks, unit conversions, |
6e-16 |
librosa’s |
STFT, ISTFT, dB, melspectrogram, MFCC, delta |
2e-12 |
3.3e-8 against librosa’s default float32 mel basis |
Spectral features, PCEN, weightings, reassigned spectrogram |
5e-11 |
|
|
1.5e-15 |
Tuning estimates identical |
|
3.3e-16 |
pYIN voiced flags identical |
Onset strength, tempograms, PLP |
3.1e-14 |
Onset and beat frames and tempi identical |
HPSS, softmask, emphasis, remix, LPC, |
6e-13 |
|
Phase vocoder, |
7e-11 |
|
DTW, Viterbi, RQA, recurrence, |
3.5e-16 |
Paths and state sequences identical |
CQT top octave |
1.7e-16 |
Lower octaves up to 1.3e-4, through the resampler |
|
68 dB SNR |
Through the resampler; depends on the signal |
|
129 to 135 dB SNR |
Middle of a band-limited signal; 50 to 58 dB on white noise |
float32 input agrees to float32 round-off, 1e-7 to 5e-6 depending on the function. The
exception is spectral_contrast on a tonal signal, up to 9.2e-3 of its range (about
0.2 dB), from float32 FFT noise in the valleys.
These do not agree, on purpose or because the implementations differ:
griffinlimwithinit="random": phases come from a different generator. Both are valid reconstructions.init=Noneagrees.window_bandwidth: librosa returns a table value for named windows; this evaluates the formula (up to 1e-4 apart).rqa: librosa stores a wrong back-pointer for a(-2, -1)move into the second column. Scores are identical; the path here follows the move taken.harmonic/percussive/harmonic_percussive:windowis used; librosa ignores it and uses Hann.time_stretchon input with exact digital silence: phases of near-zero bins are ill-conditioned, about 30 dB SNR there, as librosa against itself with a 1e-15 change.recurrence_matrix: exact neighbour search here; librosa’s scikit-learn search can differ by round-off in distances. Connectivity tie-breaking matches.
gl_ours = aus.effects.griffinlim(np.abs(D), n_iter=4, init=None)
gl_theirs = librosa.griffinlim(np.abs(D), n_iter=4, init=None)
assert relative_error(gl_ours, gl_theirs) < 1e-3
f0, flag, prob_voiced = b.pyin(fmin=65.4, fmax=2093.0)
lf0, lflag, lprob = librosa.pyin(y, fmin=65.4, fmax=2093.0, sr=sr)
assert np.array_equal(flag[0], lflag)
assert np.nanmax(np.abs(f0[0] - lf0) / lf0) < 1e-6
Recipes
Features for machine learning
A fixed-length vector per file. Method results are ordinary NumPy arrays:
def feature_vector(path):
audio = aus.io.read(path, as_type=aus.SampleType.F32).to_mono().resample(22050, "high")
mfcc = audio.mfcc_frames(n_mfcc=13, top_db=80.0)[0]
delta = aus.spectral.delta(mfcc)
centroid = audio.spectral_centroid_frames()[0]
rms = audio.rms_frames()[0]
zcr = audio.zero_crossing_rate_frames()[0]
chroma = audio.chroma_stft(tuning=None)[0]
parts = [mfcc, delta, centroid, rms, zcr, chroma]
return np.concatenate([np.r_[p.mean(axis=1), p.std(axis=1)] for p in parts])
vector = feature_vector("song.wav")
assert vector.dtype == np.float32 and vector.shape == (2 * (13 + 13 + 1 + 1 + 1 + 12),)
Batch processing a directory, with threads
File reads, to_mono, resample and the analysis methods release the GIL, so a thread
pool scales without the pickling and start-up of a process pool. librosa also speeds up with
threads. See the batch table under Evidence.
tempo’s estimate, a Python callable given as aggregate and StreamedAudioReader hold
the GIL.
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
for i in range(4):
aus.io.save(f"take{i}.wav", song)
files = sorted(Path(".").glob("take*.wav"))
with ThreadPoolExecutor(max_workers=4) as pool:
matrix = np.stack(list(pool.map(feature_vector, files)))
assert matrix.shape == (4, vector.size)
A directory of formats other than WAV and FLAC needs a decoder first; see Other file
formats. There is no equivalent of librosa.util.find_files; pathlib does it.
Beat tracking
tempo_ours, beat_times = b.beat_track(units="time", trim=True)
beat_samples = b.beat_track(units="samples", trim=True)[1]
assert np.array_equal(beat_times, beats) and beat_samples.dtype == np.int64
# A precomputed envelope, as librosa's onset_envelope= form.
envelope = b.onset_strength()[0]
tempo_env, beat_frames = aus.rhythm.beat_track(onset_envelope=envelope, sr=sr, trim=True)
theirs_env = librosa.beat.beat_track(onset_envelope=envelope, sr=sr)[1]
assert np.array_equal(beat_frames, theirs_env)
Beat tracking and onset detection need mono audio, so mix down first or loop over
extract_channel.
Harmonic-percussive separation
harmonic, percussive = b.harmonic_percussive()
h_theirs, p_theirs = librosa.effects.hpss(y)
assert relative_error(harmonic.to_numpy(), h_theirs) < 1e-5
assert relative_error(percussive.to_numpy(), p_theirs) < 1e-5
# On a spectrogram, with masks if you want them.
H, P = aus.effects.hpss(np.abs(D))
assert relative_error(H, librosa.decompose.hpss(np.abs(D))[0]) < 1e-5
mask_h, mask_p = aus.effects.hpss(np.abs(D), mask=True)
Pitch tracking with pYIN
fmin and fmax are required, as in librosa. The arrays have the channel axis, and
the float type follows the input (librosa returns float64 for float32 input):
note = aus.generation.sine_wave(220.0, 0.5, 22050, 0.5, dtype=np.float32)
f0, voiced, voiced_prob = note.pyin(fmin=65.4, fmax=2093.0)
assert f0.dtype == np.float32 and f0.shape[0] == 1
assert voiced[0, 11] and abs(f0[0, 11] - 220.0) < 2.0
Time-stretch and pitch-shift
faster = b.time_stretch(1.25)
assert relative_error(faster.to_numpy(), librosa.effects.time_stretch(y, rate=1.25)) < 1e-5
higher = b.pitch_shift(2.0)
assert higher.samples_per_channel() == y.size
# Stereo works on both; a sample type is kept.
assert stereo.time_stretch(1.25).num_channels == 2
assert naive.pitch_shift(2.0).to_numpy().dtype == np.int16
pitch_shift ends in a resampling step, so it agrees only as far as the resamplers do.
Griffin-Lim
From a magnitude spectrogram. rng is seeded by default, so repeated calls give the
same result:
magnitude = np.abs(D)
first = aus.effects.griffinlim(magnitude, n_iter=8)
second = aus.effects.griffinlim(magnitude, n_iter=8)
assert np.array_equal(first, second)
assert first.dtype == np.float32
as_audio = aus.AudioSamples.griffinlim_audio(magnitude, sample_rate=sr, n_iter=8)
assert as_audio.sample_rate == sr
griffinlim_cqt starts from zero phase unless init="random" is passed, and
librosa.feature.inverse (mel_to_audio, mfcc_to_audio and friends) is audio_samples.inverse.
Plotting
Results are NumPy arrays, so matplotlib works directly. librosa.display is not
reproduced, but nothing stops you using it on these arrays: it only needs the matrix and the
rate. audio_samples.mpl has its own plots on top of matplotlib (pip install
matplotlib seaborn), and is imported on first use.
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import librosa.display
figure, axes = plt.subplots(3, 1)
axes[0].imshow(a_S_db[0], origin="lower", aspect="auto")
librosa.display.specshow(a_S_db[0], sr=a.sample_rate, x_axis="time", y_axis="mel", ax=axes[1])
aus.mpl.plot_waveform(a, ax=axes[2])
plt.close(figure)
Example audio
librosa.ex downloads recordings. generation.example_clip synthesises its clips when asked, at the
sample rate, duration and sample type you choose, and nothing is stored or downloaded. The clips are not
librosa’s recordings, so they do not stand in for a comparison that needs those exact files. Their contents
are known, which makes them useful for checking a result: Signal Generation lists them.
# y, sr = librosa.load(librosa.ex("nutcracker"), duration=10)
clip = aus.generation.example_clip("chords_and_drums", 10.0, 22050)
assert clip.sample_rate == 22050 and clip.samples_per_channel() == 220500
Other file formats
aus.io reads WAV and FLAC only. MP3, Ogg Vorbis, Opus and AIFF raise an error, where
librosa.load handles them through libsndfile. Decode with soundfile and wrap the array,
which is what librosa.load does. soundfile returns (frames, channels); these take
(channels, frames):
import soundfile
soundfile.write("song.ogg", x.T, sr_file, format="OGG", subtype="VORBIS")
assert raises(TypeError, lambda: aus.io.read("song.ogg"))
data, rate = soundfile.read("song.ogg", dtype="float32", always_2d=True)
ogg = aus.AudioSamples.new_multi(data.T, rate)
assert ogg.num_channels == 2 and ogg.sample_rate == 44100
File objects (io.BytesIO) are not accepted either. Read the bytes with soundfile in the
same way.
To NumPy, PyTorch and scikit-learn
# NumPy, either way, without a copy when the audio wraps a NumPy array.
wrapped = aus.AudioSamples.new_mono(y, sr)
assert np.shares_memory(wrapped.to_numpy(), y)
# In-place methods therefore change the array you passed.
private = aus.AudioSamples.new_mono(y.copy(), sr)
assert not np.shares_memory(private.to_numpy(), y)
import torch
tensor = torch.from_numpy(a_mfcc) # shares memory with the array
assert tensor.dtype == torch.float32 and tuple(tensor.shape) == a_mfcc.shape
waveform = a.to_tensor(None) # None: the default device
assert waveform.dtype == torch.float32 and tuple(waveform.shape) == (a.samples_per_channel(),)
from sklearn.preprocessing import StandardScaler
scaled = StandardScaler().fit_transform(matrix)
assert scaled.shape == matrix.shape
Checking your code
python -m audio_samples.migrate lists the librosa calls in Python files and notebooks. For each one
it prints where it is, the call, the audio_samples equivalent, how closely it matches, and what to
watch for in that particular call. It reads the files and never changes them, and librosa does not have
to be installed.
python -m audio_samples.migrate src notebooks/analysis.ipynb
src/pipeline.py:12: librosa.power_to_db(S, ref=np.max)
use: spectral.power_to_db
match: equivalent
note: ref as a number, "max" or numpy.max; per-channel reference.
watch (default differs): top_db is not passed: librosa uses 80.0, audio_samples uses top_db=None. librosa applies an 80 dB floor here; pass top_db=80.0 to do the same.
1 librosa uses of 1 functions in 1 of 1 files
match: 1 equivalent, 0 with differences, 0 not provided, 0 unknown
watch: 1 default differs
blocking: 0, errors: 0
The checker parses the code with ast, so it follows import librosa as lb, from librosa.feature
import mfcc and from librosa import stft as s, and it does not report a local function that happens
to be called stft. A notebook’s location is written path:cellN:line, counting code cells from 1.
What it reports depends on the arguments in the call:
keyword changed: the keyword has another name or is not needed, for example
yandsrwhen the equivalent is a method.unsupported option: the equivalent has no such option, or rejects the value given.
sparse=Trueononset_detectpasses andsparse=Falsedoes not, and the advice namesforms.onset_detect.default differs: the two libraries use different defaults and the call relies on the default. Passing the keyword removes the warning.
shape differs: the result has another shape, usually the leading channel axis.
behaviour: anything else about the result that needs a change at the call site.
not checked: the checker could not tell, for instance because of
**optionsor a value that is not a constant.
--format json writes the findings, errors and summary as one JSON object. The exit status is 0 when there
is nothing to report, 1 when there are findings, and 2 when a path could not be read or parsed.
--fail-on selects what counts as a finding: any (the default) for any librosa use, blocking for
uses with no equivalent or with an option the equivalent rejects, and never to report without failing.
In CI, --fail-on any stops librosa coming back once a project has moved, and --fail-on blocking
shows when a project is ready to start.
The checker sees only source text. It does not follow values across calls, so it cannot tell that S in
power_to_db(S) came from melspectrogram, and it does not see a call made through getattr.
Migrating gradually
Both libraries can live in one process, and they exchange plain arrays. import
audio_samples loads only its extension, so adding it costs little until it is used.
What crossing the boundary costs. Wrapping a NumPy array in an AudioSamples and
taking it back do not copy. Audio produced by a method (resample, to_mono,
time_stretch) is held by Rust: to_numpy() then copies on each call, and
numpy.asarray keeps one shared array. Feature methods return NumPy arrays that nothing
else refers to. Measured for 60 s of float32 on the machine and date under Evidence, one core:
Operation |
Microseconds (median) |
|---|---|
new_mono (wrap a NumPy array) |
0.155 |
new_multi (wrap a NumPy array) |
0.183 |
to_numpy, audio wrapping a NumPy array |
0.057 |
numpy.asarray, audio wrapping a NumPy array |
0.539 |
to_numpy, audio made by a method (copy) |
134.91 |
numpy.asarray, audio made by a method |
0.499 |
# librosa features from audio_samples audio, and the reverse.
resampled = aus.io.read("song.wav", as_type=aus.SampleType.F32).to_mono().resample(22050, "high")
librosa_on_ours = librosa.feature.spectral_flatness(y=np.asarray(resampled))
ours_on_librosa = aus.AudioSamples.new_mono(y, sr).spectral_flatness_frames()
A sensible order.
Leave
librosa.loadfor last if you have formats other than WAV and FLAC. Otherwise convert it first and write out the rate, mix-down and type; the rest of the code keeps working on the same array throughnp.asarray.Move leaf features with exact agreement next: STFT, mel, MFCC, spectral features, chroma from an STFT. Index
[0]until the code downstream handles a channel axis.Then rhythm (onsets, tempo, beats) and pitch, whose results are identical or nearly so given identical samples.
Then effects and constant-Q transforms, which go through the resampler or iterate, so expect smaller agreement.
Replace plotting last, or keep
librosa.display.
Verifying a converted pipeline. Run the librosa pipeline and the converted one on a set of your own files and compare each stage, giving the converted stage the samples librosa used, so that a difference is pinned to one step. Keep this as a test until librosa is gone.
def compare_stage(name, ours, theirs, tolerance):
ours, theirs = np.asarray(ours), np.asarray(theirs)
if ours.ndim == theirs.ndim + 1:
ours = ours[0]
if ours.shape != theirs.shape:
raise AssertionError(f"{name}: shape {ours.shape} against {theirs.shape}")
error = relative_error(ours, theirs)
if error > tolerance:
raise AssertionError(f"{name}: relative error {error:.3g} above {tolerance:.3g}")
return error
y_lr, sr_lr = librosa.load("song.wav")
converted = aus.AudioSamples.new_mono(y_lr, sr_lr) # librosa's samples
compare_stage("stft", converted.stft_matrix(), librosa.stft(y_lr), 1e-6)
compare_stage("mel", converted.melspectrogram(), librosa.feature.melspectrogram(y=y_lr, sr=sr_lr), 1e-6)
compare_stage("onsets", converted.onset_strength(), librosa.onset.onset_strength(y=y_lr, sr=sr_lr), 1e-5)
float32 comparisons bottom out around 1e-7 to 5e-6. To check an algorithm rather than float32
round-off, convert to float64 first and pass dtype=np.float64 to librosa’s mel and chroma
functions.
When to stay on librosa
Stay, or keep librosa alongside, if any of these matter to you. Each was checked on the versions under Evidence.
Availability. The API described here is unreleased, and has only been run on x86-64 Linux with CPython 3.13. The current PyPI release lacks it. There are no wheels for macOS or Windows, so those need a Rust toolchain, and none of this has been tried there. librosa is pure Python, and its compiled dependencies publish wheels for Linux, macOS and Windows.
Maturity and breadth. audio_samples is at version 0.3.0, classified as beta, with one
listed author. librosa is at 1.0.0, has a citation helper (librosa.cite), example data and
plotting helpers. If you need a result your field will recognise as “computed with librosa”, that
counts for more than speed.
Install size of the wheel. librosa’s own wheel is pure Python, so it is smaller than this library’s compiled one. The dependencies it pulls in are a different matter.
Ours |
librosa 1.0.0 |
|
|---|---|---|
Own wheel |
7.9 MB |
0.3 MB |
Fresh environment, with dependencies |
90 MB |
486 MB |
Packages installed |
2 |
26 |
File formats and sources. WAV and FLAC only: no MP3, Ogg Vorbis, Opus or AIFF, and no file
objects. librosa.load takes all of these. The workaround is under Other file formats.
Writing FLAC from Rust. Through Python, io.save to FLAC at its default level is faster than
soundfile.write at its default, as the save rows under Evidence show. At the same compression
level, this library’s encoder is slower than libFLAC, by the ratios below; decoding is faster than
every other decoder measured. If you encode a lot of FLAC at high levels, use libFLAC.
Compression level |
Ours / libFLAC, median |
Lowest |
Highest |
|---|---|---|---|
0 |
1.69 |
1.40 |
1.87 |
5 |
1.51 |
0.92 |
1.90 |
8 |
4.22 |
1.65 |
6.37 |
Saving 24-bit stereo WAV and FLAC. io.save of 24-bit multichannel audio to WAV is slower and
uses more memory than soundfile.write, and saving FLAC holds a copy of the samples, so its peak
allocation is much higher than soundfile.write’s. See the save rows under Evidence for 16-bit.
Both come from the file library this package uses, audio_samples_io.
FLAC holds integers only. io.save to FLAC writes 16-bit or 24-bit samples and raises
ValueError for any other sample type unless as_type asks for SampleType.I16 or
SampleType.I24. WAV keeps every sample type, float64 included.
Functions with no equivalent: only librosa’s own plumbing: cache, cite,
show_versions, util.Deprecated, util.rename_kw and its exception classes. Everything else
has a counterpart: audio_samples.inverse, linalg, factorization, pitch_filterbank,
segment, notation and arrays, and mpl for librosa.display.
Options on an array form. audio_samples.forms takes the options that methods leave out: sr,
offset and duration when reading a file; several signals, pad and out when mixing channels;
scale when resampling; sparse=False in onset_detect and beat_track; S, C, V and
window given to an analysis; feature in onset_strength; freqs in tempogram_ratio;
kind and axis in salience; and axis in frame.
Options that raise here. Each was run and raises ValueError or TypeError:
sparse=Falseon the methodsonset_detectandbeat_track(see above);multichannel audio in
onset_detectandbeat_track;intervalsother than"equal"in the methodchroma_vqt: compute the transform withvqt(intervals=...)and pass it toforms.chroma_vqt;mask=Trueinharmonic,percussiveandharmonic_percussive: librosa documents the masks but returns the inverse STFT of the mask; the masks areeffects.hpss(S, mask=True);a smoothing
windowin the methodchroma_cqt: useforms.chroma_cqt;scale=Truein the methodpitch_shift: useforms.pitch_shift;a 3-D matrix in
magphase(index[0]);formats other than WAV and FLAC in
io.readandio.StreamedAudioReader;fractional sample rates.
Accepted, not applied. griffinlim(dtype=...) is ignored, and griffinlim accepts a
momentum above 1 silently where librosa warns.
Where the implementations differ. Anything downstream of soxr: if your results must match
librosa’s resample, pitch_shift or lower CQT octaves to better than 1e-4, keep librosa
for those steps.
The API is split. Methods of the library’s own API with the names you expect (rms,
stft, hpss, trim) sit beside the librosa-compatible ones, which have different names.
See Methods that are not librosa-compatible.