audioread developer on retainer: audio_open() returns native file sample rate without resampling — 44 100 Hz MP3 files processed with sr=22 050 mel filterbank; all mel frequency bins shifted 2×; music genre model accuracy 89%→54% — explicit resample fix — 3 weeks — audioread developer on monthly retainer

audioread 3.0.1 • Python 3.9; with audioread.audio_open(path) as f:; f.samplerate; mel spectrogram with hardcoded sr=22050 • Eastfield Audioread Ltd. (music genre classification service; 500,000 MP3 tracks per month; source archive encoded at 44 100 Hz; audioread.audio_open() yields audio at f.samplerate = 44100 Hz — does NOT resample; pipeline computes mel filterbank with hardcoded sr=22050 (librosa default carried over from earlier implementation); mel bins designed for 0–11 025 Hz applied to 0–22 050 Hz FFT of 44 100 Hz audio; all frequency content shifted 2× in mel space; model trained on librosa-resampled 22 050 Hz features; inference on 44 100 Hz un-resampled features; genre accuracy 89%→54%; 23% misclassification rate; fix: scipy.signal.resample_poly(audio, 22050, f.samplerate) before feature extraction; 1.5h retainer engagement

Eastfield Audioread Ltd. built a music genre classification service for a streaming platform that pre-tagged tracks from an independent label archive. The service decoded each MP3, extracted mel spectrogram features, and fed them to a scikit-learn gradient boosting classifier. The original implementation used librosa.load(path, sr=22050) for decoding and had reached 89% accuracy on the validation set. When the pipeline was rewritten for performance — librosa’s resampling step was identified as the main bottleneck, consuming 60% of per-track processing time — the developer replaced librosa.load() with a direct audioread loop to decode the compressed audio and pass the raw PCM to the feature extractor. The mel spectrogram parameters were carried over unchanged from the librosa-based implementation: sr=22050, n_fft=2048, hop_length=512. The refactored pipeline ran 3× faster. Accuracy on the development test set — a 2,000-track sample of the same archive — dropped noticeably but was attributed to a code issue in the new decoding loop that was quickly patched. When the new pipeline was promoted to production and processed the full 500,000-track archive, the streaming platform’s editorial team began reporting high misclassification rates: rock tracks tagged as electronic, classical tracks tagged as pop. After 3 weeks of incorrect tags appearing in the catalog, an audioread retainer developer was engaged.

The root cause was identified within 30 minutes by comparing a mel spectrogram from the original librosa.load() pipeline with one from the new audioread pipeline on the same track. The audioread spectrogram showed all energy shifted consistently upward by one octave: a 440 Hz guitar note (A4) appeared in the mel bin that the filterbank assigned to 880 Hz (A5). The difference was f.samplerate. librosa.load(path, sr=22050) decodes the MP3 and then resamples from 44 100 Hz to 22 050 Hz before returning. audioread.audio_open(path) decodes the MP3 and returns audio at the file’s native sample rate — 44 100 Hz in this case — without any resampling. The mel filterbank for sr=22050, n_fft=2048 distributes n_fft/2 + 1 = 1025 FFT bins across the frequency range 0–11 025 Hz (the Nyquist frequency for 22 050 Hz audio). When the same filterbank is applied to an FFT of 44 100 Hz audio, the same 1025 bins now span 0–22 050 Hz. Each mel filter center frequency — still computed assuming a 11 025 Hz ceiling — now captures energy from a frequency band that is 2× higher in the actual audio. A tone at 1 000 Hz in the audio falls into the mel bin intended for 2 000 Hz. The classifier, trained on features extracted at 22 050 Hz with correct frequency-to-mel mapping, received inference features with systematically wrong frequency assignments and produced near-random predictions. The fix was a single resample_poly call added after the audioread decoding loop: audio = scipy.signal.resample_poly(audio, 22050, f.samplerate). After resampling, the mel filterbank parameters matched the audio sample rate, frequency mapping was correct, and accuracy on the held-out test set returned to 89%.

The annotated buggy and fixed audioread decoding pipeline, with a sample rate validation helper:

# Eastfield Audioread Ltd. — audioread 3.0.1 native sample rate mismatch
# audioread 3.0.1; Python 3.9; FFmpeg 5.1; scikit-learn GBM genre classifier
# Pipeline: 44100 Hz MP3 → audioread decode → mel spectrogram (sr=22050) → classifier
# Problem: audioread yields 44100 Hz audio; mel filterbank assumes 22050 Hz
#          mel bins cover 0-22050 Hz instead of 0-11025 Hz; all frequencies 2× off
#          model trained on librosa-resampled 22050 Hz; inference at 44100 Hz
#          genre accuracy 89% → 54%; 23% misclassification for 3 weeks
# Fix: scipy.signal.resample_poly(audio, TARGET_SR, f.samplerate) before features

import numpy as np
import audioread
import scipy.signal


TARGET_SR = 22050  # Hz — mel filterbank and model training sample rate
N_FFT = 2048
HOP_LENGTH = 512
N_MELS = 128


# ── Sample rate diagnostic ───────────────────────────────────────────────────

def diagnose_audioread_samplerate(filename: str) -> None:
    """
    Log the native sample rate of an audio file as returned by audioread.
    audioread does NOT resample — it always returns f.samplerate from the file header.
    Run this on representative files from your archive to identify sample rate diversity.
    """
    with audioread.audio_open(filename) as f:
        print(f"File: {filename}")
        print(f"  audioread backend: {type(f).__module__}.{type(f).__name__}")
        print(f"  f.samplerate  = {f.samplerate} Hz  ← native file rate; NO resampling")
        print(f"  f.channels    = {f.channels}")
        print(f"  f.duration    = {f.duration:.2f} s")
        print()
        if f.samplerate != TARGET_SR:
            ratio = f.samplerate / TARGET_SR
            print(f"  WARNING: f.samplerate ({f.samplerate} Hz) != TARGET_SR ({TARGET_SR} Hz)")
            print(f"  Frequency ratio: {ratio:.4f}×")
            print(f"  A 440 Hz tone would appear at "
                  f"{440 * ratio:.0f} Hz in un-resampled mel spectrum.")
            print(f"  Fix: resample_poly(audio, {TARGET_SR}, {f.samplerate}) before features.")
        else:
            print(f"  OK: f.samplerate == TARGET_SR ({TARGET_SR} Hz) — no resampling needed.")


# ── BUGGY decoder ────────────────────────────────────────────────────────────

def decode_audio_buggy(filename: str) -> tuple[np.ndarray, int]:
    """
    BUG: assumes audioread resamples to TARGET_SR (like librosa.load() does).
    audioread yields audio at f.samplerate — the native file rate, e.g. 44100 Hz.
    For 44100 Hz MP3 with TARGET_SR=22050 mel filterbank:
      mel bins cover 0-22050 Hz instead of 0-11025 Hz; all frequencies doubled.
    Model trained on 22050 Hz data produces random predictions on 44100 Hz features.
    """
    blocks = []
    with audioread.audio_open(filename) as f:
        # BUG: f.samplerate is ignored — assumed to equal TARGET_SR
        channels = f.channels
        for block in f:
            samples = np.frombuffer(block, dtype='<i2').astype(np.float32) / 32768.0
            if channels > 1:
                samples = samples.reshape(-1, channels).mean(axis=1)
            blocks.append(samples)
    audio = np.concatenate(blocks) if blocks else np.array([], dtype=np.float32)
    return audio, TARGET_SR  # BUG: returns TARGET_SR but audio is at f.samplerate


# ── FIXED decoder ─────────────────────────────────────────────────────────────

def decode_audio_fixed(filename: str,
                       target_sr: int = TARGET_SR) -> tuple[np.ndarray, int]:
    """
    FIX: check f.samplerate after opening; resample to target_sr if needed.
    Uses scipy.signal.resample_poly for high-quality polyphase resampling.
    Returns audio at target_sr regardless of native file sample rate.
    """
    blocks = []
    native_sr = None
    channels = None

    with audioread.audio_open(filename) as f:
        native_sr = f.samplerate   # FIX: read actual sample rate
        channels = f.channels
        for block in f:
            samples = np.frombuffer(block, dtype='<i2').astype(np.float32) / 32768.0
            if channels > 1:
                samples = samples.reshape(-1, channels).mean(axis=1)
            blocks.append(samples)

    audio = np.concatenate(blocks) if blocks else np.array([], dtype=np.float32)

    if native_sr != target_sr:
        # FIX: resample from native rate to target rate
        # resample_poly uses integer GCD reduction for efficiency
        # e.g. 44100→22050: up=22050, down=44100, gcd=22050 → up=1, down=2
        audio = scipy.signal.resample_poly(audio, target_sr, native_sr).astype(np.float32)

    return audio, target_sr


# ── Frequency correctness verification ───────────────────────────────────────

def verify_frequency_mapping(filename: str, expected_hz: float = 440.0,
                              tolerance_hz: float = 5.0) -> bool:
    """
    Verify that a known test tone (expected_hz) is correctly identified after decoding.
    Requires a WAV/MP3 containing a pure tone at expected_hz.
    Checks both buggy (un-resampled) and fixed (resampled) decoders.
    """
    audio_buggy, sr_buggy = decode_audio_buggy(filename)
    audio_fixed, sr_fixed = decode_audio_fixed(filename)

    def dominant_freq(audio: np.ndarray, sr: int) -> float:
        fft_mag = np.abs(np.fft.rfft(audio[:sr]))  # first 1 second
        freqs = np.fft.rfftfreq(sr, d=1.0 / sr)
        return float(freqs[np.argmax(fft_mag)])

    dom_buggy = dominant_freq(audio_buggy, TARGET_SR)
    dom_fixed = dominant_freq(audio_fixed, sr_fixed)

    print(f"Test tone verification: expected {expected_hz:.0f} Hz")
    print(f"  Buggy decoder  dominant freq: {dom_buggy:.1f} Hz "
          f"({'PASS' if abs(dom_buggy - expected_hz) <= tolerance_hz else 'FAIL — WRONG SR'})")
    print(f"  Fixed decoder  dominant freq: {dom_fixed:.1f} Hz "
          f"({'PASS' if abs(dom_fixed - expected_hz) <= tolerance_hz else 'FAIL'})")

    return abs(dom_fixed - expected_hz) <= tolerance_hz


if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        diagnose_audioread_samplerate(sys.argv[1])
    else:
        print("Usage: python audioread_sr.py path/to/file.mp3")
        print()
        print("Root cause: audioread 3.0.1 audio_open() yields native file sample rate")
        print("  f.samplerate = 44100 Hz (not resampled to TARGET_SR=22050)")
        print("  Mel filterbank sr=22050: bins cover 0-11025 Hz")
        print("  Applied to 44100 Hz audio:  bins cover 0-22050 Hz (2× off)")
        print("  440 Hz guitar → mel bin for 880 Hz; all tones mapped 1 octave too high")
        print("  Model trained on 22050 Hz librosa features; inference at 44100 Hz")
        print("  Genre accuracy: 89% → 54%; 23% misclassification for 3 weeks")
        print()
        print("Fix: resample_poly(audio, 22050, f.samplerate) after decoding")
        print("  Genre accuracy: 89% confirmed on held-out test set; 1.5h")

How audioread’s backend-agnostic design, the absence of resampling, and mel filterbank sample rate dependencies interact — and the correct pattern for sample-rate-agnostic audio ML feature extraction

audioread’s architecture is intentionally minimal: it provides a common iteration interface over raw 16-bit PCM bytes from whatever backend is available (FFmpeg via subprocess, GStreamer via gi.repository, macOS AudioToolbox via ctypes, Windows mediaobj via ctypes). The returned bytes are always 16-bit signed little-endian integers, and the returned samplerate and channels attributes are read from the codec’s output. The backend list is tried in order: FFmpeg (via ffmpeg or avconv subprocess) is preferred; if unavailable, GStreamer is tried; if unavailable, platform-native backends are used. Each backend delegates sample rate conversion, channel mixing, and format conversion to the underlying codec. If the codec is asked to decode at a rate different from the native file rate, the codec may or may not comply — audioread makes no such request; it accepts whatever the codec outputs. librosa’s design is the opposite: librosa.load(path, sr=22050) explicitly passes the target sample rate to audioread’s optional samplerate parameter, and when that is not honoured by the backend, librosa applies its own resampling pass using resampy or scipy after decoding. When developers switch from librosa to direct audioread usage for performance, they lose this resampling layer without realising it. The practical guidance: for any audio ML pipeline that extracts frequency-domain features with a fixed sr parameter, the sample rate of the decoded audio must be verified and standardised before feature extraction. The correct pattern is: (1) decode with audioread; (2) check f.samplerate; (3) if f.samplerate != target_sr, apply scipy.signal.resample_poly(audio, target_sr, f.samplerate). For music archives, typical native rates are 44100 Hz (CD, most MP3) and 48000 Hz (broadcast, some streaming encodes). For voice archives: 16000 Hz (telephony, ASR), 22050 Hz (some TTS), 44100 Hz (studio recordings). Never hardcode a sample rate assumption in feature extraction code without asserting or enforcing it at the decoding layer. The retainer engagement was 1.5h: 0.5h triage (genre accuracy regression; mel spectrogram comparison between old librosa pipeline and new audioread pipeline on 10 test tracks; systematic energy shift of approximately one octave confirmed; f.samplerate = 44100 confirmed in audioread output on first inspected track); 0.5h root cause (librosa resampling vs audioread pass-through confirmed in librosa source; mel filterbank frequency mapping calculated for sr=22050 vs sr=44100; 2× frequency shift arithmetic confirmed; training data was librosa-resampled 22050 Hz; inference data is audioread 44100 Hz; model accuracy at chance level on frequency-sensitive features confirmed); 0.25h fix (resample_poly(audio, 22050, f.samplerate) inserted after audioread loop; sr=22050 enforced for all decodings); 0.25h validation (440 Hz test tone FFT peak at 440 Hz ± 2 Hz confirmed; mel spectrogram visually matches librosa baseline; model accuracy 89% on 24-track held-out set; 1.5h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →