samplerate developer on retainer: samplerate.resample() ratio is output_sr/input_sr — developer writes input_sr/output_sr; 44100 Hz to 16000 Hz produces 2.756× longer audio at sub-bass pitch; Whisper transcription garbled; 20 000 interview files per month produce unusable transcripts — ratio inversion fix — 3 weeks — python-samplerate developer on monthly retainer

python-samplerate 0.1.3 • Python 3.9; samplerate.resample(audio, ratio, converter_type); ratio = output_sr / input_sr • Southfield Samplerate Ltd. (voice transcription service; 20,000 interview recordings/month from 800 journalists; source: 44100 Hz MP3 (majority), 48000 Hz WAV (some), 22050 Hz MP3 (some); target: 16000 Hz for Whisper; ratio=source_sr/target_sr written instead of target_sr/source_sr; for 44100→16000: ratio = 2.756 instead of 0.363; output 2.756× too long; audio pitch-shifted to sub-bass; Whisper WER 95%+; 20,000 files/month produce garbled transcripts for 3 weeks; fix: ratio = target_sr / source_sr; 1.5h retainer engagement)

Southfield Samplerate Ltd. built a voice transcription service for a journalism platform that allowed freelance journalists and researchers to submit recorded interviews and receive automated transcripts powered by OpenAI’s Whisper large-v2 model. Whisper requires 16000 Hz mono audio input. The journalists submitted recordings from a variety of devices: digital voice recorders producing 44100 Hz MP3 files (the most common), broadcast-quality recorders producing 48000 Hz WAV files, and some older recorders producing 22050 Hz MP3 files. The preprocessing pipeline used python-samplerate to convert all source audio to 16000 Hz before passing to Whisper. The resampling call was: resampled = samplerate.resample(audio, ratio=source_sr/target_sr, converter_type='sinc_best'). The engineer who wrote this line had the mathematical intuition that “to get from 44100 to 16000, divide 44100 by 16000” — a reasonable heuristic that unfortunately produces the inverse of the required ratio.

samplerate.resample() defines ratio as output_sample_rate / input_sample_rate: the number of output samples per input sample. For downsampling from 44100 Hz to 16000 Hz, the correct ratio is 16000/44100 = 0.3628. The output array has len(input) × ratio = 441000 × 0.3628 = 160,075 samples. Played back at 16000 Hz, this is 10.00 seconds — the original interview at the correct pitch. The inverted ratio 44100/16000 = 2.756 produced an output of 441000 × 2.756 = 1,215,396 samples. Played back at 16000 Hz, these 1.2 million samples play for 75.96 seconds — the original 10-second clip time-stretched to 76 seconds at 2.756× slower speed. The fundamental frequency of the speakers’ voices was correspondingly pitch-shifted down by a factor of 2.756: a 150 Hz speaking voice became 54 Hz, well below the typical human speech range. Whisper received files that were labeled as 16000 Hz but contained audio that had been synthesized at 2.756× the correct length and shifted to sub-bass frequencies. Whisper’s acoustic model, trained on correctly-sampled speech, produced word error rates of 93–97% on every file. The same inversion applied to 48000 Hz source audio produced ratio = 3.0, stretching 10-second clips to 30 seconds. For 22050 Hz source audio, ratio = 1.378, stretching 10-second clips to 13.78 seconds (and shifting voice to 108 Hz, still below normal speech pitch). libsamplerate accepted all three inverted ratios without error or warning — all were within its valid range of 1/256 to 256. The transcript text for every file was gibberish: Whisper returned sequences of random words, often in languages other than the interview language (a known artifact of Whisper hallucinating on inputs it cannot recognize as speech). The engineering team spent three weeks investigating Whisper model degradation, language detection configuration, and input file format issues before checking the output resampled array length and discovering it was 2.756× longer than expected.

The annotated buggy and fixed python-samplerate resampling pipeline, with ratio direction validation:

# Southfield Samplerate Ltd. — python-samplerate 0.1.3 ratio inversion fix
# python-samplerate 0.1.3; Python 3.9; Whisper voice transcription preprocessing
# 20,000 interview recordings/month from 800 journalists
# Source sample rates: 44100 Hz (MP3), 48000 Hz (WAV), 22050 Hz (MP3)
# Target: 16000 Hz mono (Whisper large-v2 requirement)
# Problem: samplerate.resample(audio, ratio) requires ratio = output_sr/input_sr
#          Developer writes ratio = source_sr/target_sr (inverted)
#          44100→16000: ratio=2.756 instead of 0.363; output 2.756x too long
#          Audio pitch-shifted to sub-bass; Whisper WER 95%+
#          20,000 files/month produce garbled transcripts for 3 weeks
# Fix: ratio = target_sr / source_sr (flip the fraction)

import numpy as np
import soundfile
import samplerate


# ── BUGGY resampling pipeline ─────────────────────────────────────────────────

def resample_for_asr_buggy(input_path: str, output_path: str,
                             target_sr: int = 16000) -> None:
    """
    BUG: ratio = source_sr / target_sr is the WRONG direction.

    samplerate.resample(audio, ratio) defines ratio as output_sr/input_sr.
    output_length = int(input_length * ratio)

    With inverted ratio for 44100 Hz → 16000 Hz:
      ratio = 44100 / 16000 = 2.75625  (WRONG — this is input/output, not output/input)
      output_length = 441000 * 2.756 = 1,215,396 samples
      At 16000 Hz: 1,215,396 / 16000 = 75.96 seconds (should be 10 seconds)
      Pitch shift: voice at 150 Hz → 150 / 2.756 = 54 Hz (sub-bass, unintelligible)
      Whisper WER: 95%+ on all files

    With inverted ratio for 48000 Hz → 16000 Hz:
      ratio = 48000 / 16000 = 3.0  (WRONG)
      output: 3x too long; Whisper WER 95%+

    With inverted ratio for 22050 Hz → 16000 Hz:
      ratio = 22050 / 16000 = 1.378  (WRONG)
      output: 1.378x too long; voice pitch 150 Hz → 109 Hz; Whisper WER 85%+
    """
    audio, source_sr = soundfile.read(input_path, always_2d=False)
    if audio.ndim > 1:
        audio = audio.mean(axis=1)   # stereo → mono
    audio = audio.astype(np.float32)

    if source_sr != target_sr:
        # BUG: ratio is inverted — source/target instead of target/source
        ratio = source_sr / target_sr   # WRONG: 44100/16000 = 2.756
        resampled = samplerate.resample(audio, ratio, converter_type='sinc_best')
    else:
        resampled = audio

    soundfile.write(output_path, resampled, target_sr)


# ── FIXED resampling pipeline ─────────────────────────────────────────────────

def resample_for_asr_fixed(input_path: str, output_path: str,
                             target_sr: int = 16000) -> None:
    """
    FIX: ratio = target_sr / source_sr (output rate over input rate).

    samplerate.resample(audio, ratio) semantic:
      ratio = output_sample_rate / input_sample_rate
      output_length = int(input_length * ratio)

      ratio > 1.0 → upsampling (output longer than input)
      ratio < 1.0 → downsampling (output shorter than input)
      ratio = 1.0 → no change

    For downsampling 44100 Hz → 16000 Hz:
      ratio = 16000 / 44100 = 0.36281  ← correct
      output_length = 441000 * 0.363 = 160,083 samples
      At 16000 Hz: 10.00 seconds  ← correct duration
      Voice pitch: unchanged  ← correctly resampled

    For 48000 Hz → 16000 Hz:
      ratio = 16000 / 48000 = 0.3333  ← correct

    For 22050 Hz → 16000 Hz:
      ratio = 16000 / 22050 = 0.7256  ← correct
    """
    audio, source_sr = soundfile.read(input_path, always_2d=False)
    if audio.ndim > 1:
        audio = audio.mean(axis=1)   # stereo → mono
    audio = audio.astype(np.float32)

    if source_sr == target_sr:
        soundfile.write(output_path, audio, target_sr)
        return

    # Validate ratio direction before resampling.
    ratio = target_sr / source_sr   # output_sr / input_sr — always this order
    _validate_ratio(ratio, source_sr, target_sr, len(audio))

    resampled = samplerate.resample(audio, ratio, converter_type='sinc_best')

    # Post-resample length check (defensive — catches future ratio inversions).
    expected_length = int(len(audio) * ratio)
    actual_length = len(resampled)
    if abs(actual_length - expected_length) > 2:
        raise RuntimeError(
            f"samplerate.resample: unexpected output length. "
            f"Expected {expected_length} samples, got {actual_length}. "
            f"ratio={ratio:.6f}, source_sr={source_sr}, target_sr={target_sr}. "
            f"If output is {source_sr/target_sr:.3f}x longer than expected, "
            f"the ratio is inverted — check: ratio = target_sr/source_sr not source_sr/target_sr."
        )

    soundfile.write(output_path, resampled, target_sr)


def _validate_ratio(ratio: float, source_sr: int, target_sr: int,
                     input_length: int) -> None:
    """
    Validate ratio direction and plausibility before resampling.
    Raises ValueError with a helpful diagnostic message if validation fails.
    """
    is_downsampling = target_sr < source_sr
    is_upsampling = target_sr > source_sr

    if is_downsampling and ratio >= 1.0:
        raise ValueError(
            f"samplerate ratio error: downsampling {source_sr} Hz → {target_sr} Hz "
            f"requires ratio < 1.0, got ratio={ratio:.6f}. "
            f"Ratio is likely inverted: ratio={source_sr}/{target_sr}={ratio:.4f} "
            f"instead of ratio={target_sr}/{source_sr}={target_sr/source_sr:.4f}. "
            f"Output would be {ratio:.2f}x longer than input ({int(input_length*ratio)} samples "
            f"instead of {int(input_length*(target_sr/source_sr))} samples); "
            f"audio would be pitch-shifted to {ratio:.2f}x lower frequency."
        )

    if is_upsampling and ratio <= 1.0:
        raise ValueError(
            f"samplerate ratio error: upsampling {source_sr} Hz → {target_sr} Hz "
            f"requires ratio > 1.0, got ratio={ratio:.6f}. "
            f"Ratio is likely inverted: ratio={source_sr}/{target_sr}={ratio:.4f} "
            f"instead of ratio={target_sr}/{source_sr}={target_sr/source_sr:.4f}. "
            f"Output would be {ratio:.2f}x shorter than input."
        )


# ── Converter type reference ──────────────────────────────────────────────────

CONVERTER_TYPES = {
    # Sinc interpolation converters (all correct — differ in CPU vs quality trade-off)
    'sinc_best':    'Highest quality. ~20x slower than sinc_fastest. Use for archival.',
    'sinc_medium':  'Good quality. ~6x slower than sinc_fastest. Use for batch.',
    'sinc_fastest': 'Fastest sinc. Adequate for ASR preprocessing. 16000 Hz target.',
    # Non-sinc (fast but low quality — not recommended for speech)
    'zero_order_hold': 'Fastest. Staircase artifacts. Only for extreme CPU constraints.',
    'linear':          'Fast. Linear interpolation. Audible aliasing on speech.',
}


if __name__ == '__main__':
    # Diagnostic: show ratio and expected output length for common conversions.
    SOURCE_RATES = [44100, 48000, 22050, 32000, 96000]
    TARGET_SR = 16000
    print(f"{'Source Hz':>10}  {'Correct ratio':>15}  {'Inverted ratio':>15}  "
          f"{'Output (10s)':>14}  {'Wrong output (10s)':>20}")
    for sr in SOURCE_RATES:
        ratio = TARGET_SR / sr
        inv_ratio = sr / TARGET_SR
        correct_len = int(sr * 10 * ratio)
        wrong_len = int(sr * 10 * inv_ratio)
        print(f"{sr:>10}  {ratio:>15.6f}  {inv_ratio:>15.6f}  "
              f"{correct_len:>14,}  {wrong_len:>20,}")

How libsamplerate’s output/input ratio convention, the absence of direction validation in the API, and ASR models’ sensitivity to pitch shift interact — and the correct pattern for production-grade audio resampling pipelines

libsamplerate (and its Python wrapper python-samplerate) defines ratio = output_sample_rate / input_sample_rate because this is the natural definition from the sample rate converter’s internal perspective: the converter produces ratio output samples for each input sample. This convention means “downsampling” is a ratio less than 1.0, and “upsampling” is a ratio greater than 1.0 — the opposite of what many engineers expect from the intuition “I need to divide by the downsampling factor.” The confusion is systematic: the phrase “resample from 44100 to 16000” induces the mental model “divide 44100 by something to get 16000”, which leads directly to ratio = 44100/16000 = 2.756. The correct computation — ratio = 16000/44100 = 0.3628 — involves dividing the smaller target by the larger source, which feels counter-intuitive to engineers who associate “downsampling” with dividing by an integer factor. The absence of a range check on the ratio does not help: libsamplerate accepts ratios between 1/256 and 256, so 2.756 is accepted without warning even though it produces dramatically wrong output for a 44100 Hz to 16000 Hz conversion. The diagnostic is reliable: check the output array length. The correct output for a 10-second 44100 Hz clip resampled to 16000 Hz has 160,075 samples. The inverted ratio produces 1,215,396 samples — 7.6× more than expected. The ratio direction error — source/target instead of target/source — produces an output that is (source/target)^2 times longer than the correct output: for 44100 Hz to 16000 Hz, (2.756)^2 = 7.6. The _validate_ratio() function catches the inversion before any samples are processed: when downsampling (target_sr < source_sr), ratio must be < 1.0 — a ratio ≥ 1.0 for a declared downsampling operation is a reliable indicator of inversion. This check is zero-cost and prevents 20,000 files per month from being processed into unusable outputs. The pitch shift effect — voice fundamental at 150 Hz shifted to 54 Hz — is perceptually dramatic but diagnostically subtle when the pipeline outputs a WAV file labeled as 16000 Hz: a quick visual inspection of the output file shows the right sample rate and roughly the right duration (since the transcription platform truncates output at 30 minutes), and only listening to the output or checking the sample count reveals the error. The retainer engagement was 1.5h: 0.5h triage (95%+ WER on all Whisper outputs; output WAV files 2.756× expected duration; listen to resampled audio confirms sub-bass pitch shift; check output sample count: 1,215,506 instead of expected 160,083 for 10-second 44100 Hz clip; ratio computation confirmed inverted); 0.5h root cause (python-samplerate ratio convention confirmed as output/input from docs and libsamplerate reference manual; inverted ratio produces pitch-shifted time-stretched output confirmed by arithmetic); 0.25h fix (ratio = target_sr / source_sr; validate for all 3 source rates; _validate_ratio() guard added); 0.25h validation (100-file test: output durations match input durations within 1 sample; Whisper WER 4.2%; 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 →