wavio developer on retainer: 24-bit WAV normalization divides by np.iinfo(int32).max = 2 147 483 647 instead of 2**(wav.sampwidth×8−1) = 8 388 608 — audio 256× too quiet; mel spectrograms dominated by noise floor; audio classification model accuracy 94%→61% — sampwidth fix — 3 weeks — wavio developer on monthly retainer

wavio 0.0.9 • Python 3.9; wav = wavio.read(filename); audio = wav.data.astype(np.float32) / np.iinfo(wav.data.dtype).max • Southfield Wavio Ltd. (audio quality classification ML pipeline; 5,000 professional studio WAV files per month; 24-bit source files from recording studios, wav.sampwidth = 3; wavio 0.0.9 reads 24-bit WAV as int32 NumPy array; sample values in int24 range [−8 388 608, +8 388 607]; developer normalizes with np.iinfo(wav.data.dtype).max = np.iinfo(np.int32).max = 2 147 483 647; correct divisor for 24-bit = 2**(3×8−1) = 2**23 = 8 388 608; normalization ratio 1/256 = −48.1 dBFS too quiet; mel spectrograms show near-uniform noise floor; scikit-learn random forest classifier trained on 16-bit dev data; inference on 24-bit production data 61% accuracy; 23% of studio files misclassified for 3 weeks; fix: audio = wav.data.astype(np.float32) / (2 ** (wav.sampwidth * 8 - 1)); 1.5h retainer engagement

Southfield Wavio Ltd. built an audio quality classification pipeline for a music distribution company that accepts master recordings from professional studios. The pipeline classified incoming WAV files for audio quality issues — clipping, excessive dynamic range compression, low-frequency hum, and high-frequency noise — before routing them to mastering. The developer used wavio to read WAV files directly into NumPy arrays because the studio archive contained 24-bit WAV files, and scipy.io.wavfile silently returns incorrect data for 24-bit files (it returns an int32 array where the 24-bit values are left-shifted by 8 bits rather than sign-extended). Development and training used a dataset of 16-bit WAV files from an internal archive. The normalization code was written once during the development phase: audio = wav.data.astype(np.float32) / np.iinfo(wav.data.dtype).max. For 16-bit WAV files (sampwidth=2), wav.data.dtype is int16 and np.iinfo(np.int16).max = 32767 — the correct divisor for int16-to-float normalization. The model reached 94% accuracy on the 16-bit validation set. When production ingestion switched to the studio archive of 24-bit files, the pipeline appeared to run without errors. The model was scoring every file and returning predictions. But the accuracy reports from the mastering team began tracking an unusually high rejection rate. After 3 weeks, a wavio retainer developer was engaged when a mastering engineer noticed that files flagged for “clipping” were clearly clean recordings.

Inspection of the normalization output identified the issue immediately. For 24-bit WAV files, wavio.read() returns a NumPy array with dtype=int32. The array contains the 24-bit sample values stored in the lower 24 bits of each int32 element — the values are in the range [−8 388 608, +8 388 607] (the int24 value range, 223). But wav.data.dtype is np.int32, and np.iinfo(np.int32).max is 2 147 483 647 (231−1). Dividing a full-scale 24-bit sample value of 8 388 607 by 2 147 483 647 gives 0.00390625 — exactly 1/256 of the correct normalized value. The mel spectrogram of audio at −48.1 dBFS consists almost entirely of noise floor. The random forest classifier, trained on correctly normalized 16-bit audio where energy was distributed across mel bins at proper levels, could extract no meaningful features from the near-silent 24-bit input. Its predictions were functionally random — near chance level on a 5-class problem. The fix was a single-line change: replace the dtype-based divisor with a sampwidth-derived divisor. wav.sampwidth is the bytes-per-sample value read from the WAV file header (1, 2, 3, or 4). The correct maximum for any WAV bit depth is 2 ** (wav.sampwidth * 8 - 1): for 16-bit this gives 32768 (within floating point rounding of 32767); for 24-bit it gives 8388608. After the fix, 24-bit audio normalized correctly to [−1.0, +1.0] and model accuracy on the 24-bit test set matched the training-set accuracy at 94%.

The annotated buggy and fixed wavio normalization code, with a bit-depth validation helper:

# Southfield Wavio Ltd. — wavio 0.0.9 24-bit WAV normalization divisor error
# wavio 0.0.9; Python 3.9; NumPy 1.24
# Pipeline: 24-bit professional studio WAV → normalize → mel spectrogram → classifier
# Problem: np.iinfo(wav.data.dtype).max = int32 max (2^31-1) for 24-bit WAV
#          actual int24 max = 2^23 = 8388608; ratio 1/256 = -48.1 dBFS too quiet
#          mel spectrograms show noise floor only; model accuracy 94%→61%
# Fix: 2 ** (wav.sampwidth * 8 - 1) uses sampwidth to compute correct divisor

import numpy as np
import wavio


# ── WAV normalization diagnostic ─────────────────────────────────────────────

def diagnose_wavio_normalization(filename: str) -> None:
    """
    Log normalization values for a WAV file at all bit depths.
    Run on a known full-scale test tone to verify normalization correctness.
    """
    wav = wavio.read(filename)

    dtype_max = np.iinfo(wav.data.dtype).max
    sampwidth_max = 2 ** (wav.sampwidth * 8 - 1)
    bit_depth = wav.sampwidth * 8

    print(f"File: {filename}")
    print(f"  Rate: {wav.rate} Hz")
    print(f"  Bit depth: {bit_depth}-bit (sampwidth={wav.sampwidth})")
    print(f"  Array dtype: {wav.data.dtype}")
    print(f"  Sample count: {len(wav.data)}")
    print(f"  Peak sample value: {wav.data.max()} (min: {wav.data.min()})")
    print()
    print(f"  np.iinfo(dtype).max  = {dtype_max:>15,}  ← WRONG for {bit_depth}-bit WAV")
    print(f"  2**(sampwidth*8-1)   = {sampwidth_max:>15,}  ← CORRECT for {bit_depth}-bit WAV")
    print()

    buggy_peak  = wav.data.max() / dtype_max
    correct_peak = wav.data.max() / sampwidth_max

    print(f"  Buggy normalization peak:   {buggy_peak:.6f}  "
          f"({20*np.log10(max(buggy_peak, 1e-9)):.1f} dBFS)")
    print(f"  Correct normalization peak: {correct_peak:.6f}  "
          f"({20*np.log10(max(correct_peak, 1e-9)):.1f} dBFS)")

    if wav.sampwidth == 2:
        # For 16-bit, both are approximately correct (32767 vs 32768 <0.003 dBFS)
        print("  For 16-bit WAV: difference is negligible (<0.003 dBFS).")
    elif wav.sampwidth == 3:
        ratio_db = 20 * np.log10(dtype_max / sampwidth_max)
        print(f"  For 24-bit WAV: buggy normalization is {ratio_db:.1f} dBFS too quiet!")
        print("  ML models trained on correctly-normalized audio will misclassify.")


# ── BUGGY normalization ───────────────────────────────────────────────────────

def load_wav_buggy(filename: str) -> tuple[np.ndarray, int]:
    """
    BUG: divides by np.iinfo(wav.data.dtype).max.
    For 16-bit WAV (dtype=int16): max = 32767 — approximately correct.
    For 24-bit WAV (dtype=int32): max = 2147483647 — 256× too large.
    24-bit audio normalized to 1/256 of correct range (-48.1 dBFS).
    ML models receive near-silent audio; mel spectrograms show noise floor only.
    """
    wav = wavio.read(filename)
    # BUG: dtype max is correct for int16 but wrong for int32 from 24-bit WAV
    audio = wav.data.astype(np.float32) / np.iinfo(wav.data.dtype).max
    return audio, wav.rate


# ── FIXED normalization ────────────────────────────────────────────────────────

def load_wav_fixed(filename: str) -> tuple[np.ndarray, int]:
    """
    FIX: use wav.sampwidth to compute bit-depth-correct normalization divisor.
    2 ** (wav.sampwidth * 8 - 1) is the correct peak value for any PCM bit depth:
      8-bit  (sampwidth=1): 2^7  = 128
      16-bit (sampwidth=2): 2^15 = 32768
      24-bit (sampwidth=3): 2^23 = 8388608
      32-bit (sampwidth=4): 2^31 = 2147483648
    Handles mixed 16-bit/24-bit archives correctly without special-casing.
    """
    wav = wavio.read(filename)
    # FIX: sampwidth-based divisor is correct for all PCM bit depths
    divisor = 2 ** (wav.sampwidth * 8 - 1)
    audio = wav.data.astype(np.float32) / divisor

    # Verify: peak should be in (-1.0, +1.0] for non-clipped audio
    peak = float(np.abs(audio).max())
    if peak > 1.0:
        import warnings
        warnings.warn(
            f"Audio peak {peak:.4f} > 1.0 after normalization in {filename!r}. "
            "File may be clipped or use a non-standard bit depth."
        )
    return audio, wav.rate


# ── Normalization verification ────────────────────────────────────────────────

def verify_normalization(filename: str, expected_peak_db: float = -6.0,
                         tolerance_db: float = 0.5) -> bool:
    """
    Verify normalized peak amplitude matches expected level.
    For a -6 dBFS test tone: expected_peak_db = -6.0, peak amplitude ≈ 0.5.
    """
    audio, rate = load_wav_fixed(filename)
    peak = float(np.abs(audio).max())
    peak_db = 20 * np.log10(peak) if peak > 0 else -120.0

    within_tolerance = abs(peak_db - expected_peak_db) <= tolerance_db
    print(f"Normalization check: {filename!r}")
    print(f"  Peak: {peak:.5f} ({peak_db:.2f} dBFS), "
          f"expected: {expected_peak_db:.1f} dBFS ± {tolerance_db} dB")
    print(f"  {'PASS' if within_tolerance else 'FAIL'}")
    return within_tolerance


if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        diagnose_wavio_normalization(sys.argv[1])
    else:
        print("Usage: python wavio_normalize.py path/to/file.wav")
        print()
        print("Root cause: wavio 0.0.9 reads 24-bit WAV as int32 array")
        print("  np.iinfo(np.int32).max = 2,147,483,647")
        print("  int24 actual max       = 8,388,607  (2^23 - 1)")
        print("  Ratio: 1/256 = -48.1 dBFS — 24-bit audio 256× too quiet")
        print("  ML model accuracy: 94% (16-bit) → 61% (24-bit mismatch)")
        print()
        print("Fix: 2 ** (wav.sampwidth * 8 - 1)")
        print("  Correct normalization for 16-bit and 24-bit sources")
        print("  Model accuracy: 94% on 24-bit test set; 1.5h")

How wavio’s int32 storage for 24-bit samples, NumPy dtype range functions, and WAV bit-depth normalization interact — and the correct bit-depth-agnostic normalization pattern for mixed WAV archives

The WAV file format stores integer PCM samples at a bit depth specified by the wBitsPerSample header field. Standard bit depths are 8, 16, 24, and 32 bits. NumPy’s integer dtype family includes uint8, int16, int32, and int64 — there is no int24 dtype. For 24-bit WAV files, every library that uses NumPy must choose a container type. wavio 0.0.9 reads 24-bit samples into int32 arrays. The 3-byte samples from the file are sign-extended into 4-byte int32 values, preserving the original 24-bit value range [−8 388 608, +8 388 607] exactly. The int32 container adds no sign-shifting or left-padding. scipy.io.wavfile, by contrast, left-shifts the 24-bit values by 8 bits when packing into int32, so the value range spans [−2 147 483 648, +2 147 450 816] — requiring division by 2**31 for normalization. The two libraries use the same container dtype but completely different value encodings for 24-bit WAV, so normalization code is not interchangeable between them. The root of this retainer engagement was writing normalization code with the scipy.io.wavfile mental model while using wavio. The correct normalization formula for wavio is 2 ** (wav.sampwidth * 8 - 1): the -1 accounts for the sign bit, so for 24-bit (sampwidth=3): 2 ** (3*8-1) = 2**23 = 8388608, and for 16-bit (sampwidth=2): 2 ** (2*8-1) = 2**15 = 32768. Note that np.iinfo(np.int16).max = 32767 (215−1) while the formula gives 32768 (215); the difference is 0.003 dBFS and negligible for ML applications. For 24-bit the gap is catastrophic: 8388607 (dtype max) versus 8388608 (correct formula) differs by <0.00001 dBFS, but using 2147483647 (the int32 max) instead differs by 48.1 dBFS. For production pipelines ingesting mixed 16-bit and 24-bit archives, the wav.sampwidth-based formula is the only correct normalization approach. The retainer engagement was 1.5h: 0.5h triage (model accuracy regression on production 24-bit files; mel spectrogram log-energy comparison between dev and production data shows −48 dBFS offset; normalization formula identified as the site of discrepancy); 0.5h root cause (wavio 0.0.9 source confirmed: 24-bit samples stored as sign-extended int32 in native int24 range; np.iinfo(np.int32).max = 2147483647 versus correct int24 peak = 8388607; ratio = 1/256 = −48.1 dBFS confirmed by measurement on known test tone); 0.25h fix (2 ** (wav.sampwidth * 8 - 1) divisor; correct peak confirmed within 0.1% on −6 dBFS test tone at both 16-bit and 24-bit); 0.25h validation (model accuracy 94% on 24-bit held-out test set; normalization unit tests pass for all three common bit depths; 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 →