resampy developer on retainer: stereo (N, 2) arrays resampled on channel axis instead of time axis — axis=−1 default resamples 2-element channel pair, not 48 kHz → 44.1 kHz time series — axis=0 fix — 3 weeks — resampy developer on monthly retainer
resampy 0.4.3 • Python 3.9; bandlimited sinc-interpolation audio resampling library; resampy.resample(audio, sr_orig=48000, sr_new=44100) • podcast audio normalization service (15,000 stereo podcast episodes/month submitted by podcast production studios; episodes recorded on professional interfaces at 48,000 Hz; pipeline normalizes to −16.0 LUFS-I at 44,100 Hz before distribution; 12% of episodes are stereo 48,000 Hz WAV loaded with soundfile.read(path, always_2d=True) returning shape (N, 2)); resampy.resample(x, 48000, 44100) defaults axis=−1; for shape (N, 2) axis=−1 is axis 1 (the channel axis, length 2), not axis 0 (the time axis, length N); resampy resamples the 2-element channel pair at each time step instead of the N-frame time series; output shape (N, 2) — same as input; time axis N unchanged; audio content is at 48,000 Hz but file tagged 44,100 Hz; playback rate 48000/44100 = 1.088×; audio 8.8% too fast; pitch 1.47 semitones sharp; 1,800 stereo 48 kHz episodes/month play at wrong speed and pitch; listener complaints: 1,800/month; fix: resampy.resample(x, 48000, 44100, axis=0); corrupted episodes: 1,800 → 0; 1.5h retainer engagement
Southfield Resampy Ltd. had built a podcast audio normalization pipeline for a podcast distribution platform. Production studios submitted stereo master files in a mix of formats and sample rates; the pipeline normalized all audio to −16.0 LUFS-I at 44,100 Hz (Apple Podcasts distribution spec) using a chain of: soundfile read → resampy resample to 44100 Hz → pyloudnorm measure → apply loudness gain → soundfile write. The pipeline had been processing mono 44100 Hz files correctly for two months before a new studio partnership began submitting stereo 48000 Hz WAV masters (professional studio output from Pro Tools and Reaper sessions). Within the first week, the studio submitted a listener complaint: “All 60 episodes we uploaded last week play at the wrong speed — they’re about 8% too fast and the host’s voice is noticeably higher-pitched than on our reference files.” The platform’s internal QA team confirmed the issue: every stereo 48000 Hz file uploaded by that studio had the speed and pitch issue; mono files and stereo files that were already at 44100 Hz were unaffected. The pipeline had processed 1,800 stereo 48 kHz episodes that month, all of them corrupted. A resampy retainer developer was engaged to identify why the resampling step was silently producing wrong-rate output for stereo 48 kHz files.
The developer began with a minimal reproduction: load a stereo 48000 Hz WAV with soundfile.read(path, always_2d=True), call resampy.resample(audio, 48000, 44100) (no explicit axis), and check the output shape and sample count. The input array had shape (220500, 2) — 4.59 seconds of stereo audio at 48000 Hz (220500 = 4.59 × 48000). The expected output shape for a correct 48000 → 44100 resample was (202,500, 2) — 4.59 × 44100 = 202,500 samples. The actual output shape was (220500, 2) — the same as the input, with no change to the time axis. Inspecting the resampy source, the developer confirmed the issue: resampy.resample(x, sr_orig, sr_new) defaults to axis=-1, which for a 2D array of shape (N, 2) is axis 1 (length 2), not axis 0 (length N). resampy had computed the output length along axis 1 as round(2 × 44100/48000) = round(1.8375) = 2 (the two channel values resampled from 48000 to 44100 — still 2 elements), applied its sinc interpolation filter to each 2-element “signal” row-by-row, and returned an (N, 2) array. The time axis was completely unmodified. The audio content remained at 48000 Hz but the pipeline wrote it to a 44100 Hz WAV file, causing players to interpret 48000 content samples as 44100-Hz audio — playing the file at 48000/44100 = 1.088 times normal speed, 1.47 semitones sharp. No exception was raised because the output shape (N, 2) looked correct to the pipeline. The fix was resampy.resample(audio, 48000, 44100, axis=0), explicitly specifying the time axis. Output shape became (202500, 2) as expected; measured playback pitch on a 1000 Hz test tone was 1000.4 Hz (within tolerance); all 1,800 previously-corrupted episode types were reproduced correctly with zero speed/pitch complaints.
The diagnostic code that confirmed the axis error and the axis-safe resampling wrapper:
# Southfield Resampy Ltd. — resampy 0.4.3 axis=-1 wrong axis for stereo arrays
# resampy 0.4.3; Python 3.9
# Deployment: podcast audio normalization service, 15,000 episodes/month
# Problem: axis=-1 resamples channel axis (length 2) not time axis (length N)
# Fix: axis=0 for soundfile (N, channels) arrays
import numpy as np
import resampy
import soundfile as sf
SR_SRC = 48000
SR_DST = 44100
def resample_buggy(audio: np.ndarray, sr_orig: int, sr_new: int) -> np.ndarray:
"""
Original implementation — no explicit axis.
resampy defaults axis=-1; for (N, 2) arrays this is the channel axis.
Output shape (N, 2) — time axis unchanged; audio at wrong speed.
"""
return resampy.resample(audio, sr_orig, sr_new) # bug: axis=-1 default
def resample_fixed(audio: np.ndarray, sr_orig: int, sr_new: int) -> np.ndarray:
"""
Fixed implementation — explicit axis=0 for soundfile (N, channels) arrays.
Resamples along the time axis; output shape (N * sr_new / sr_orig, channels).
"""
return resampy.resample(audio, sr_orig, sr_new, axis=0) # fix: time axis
def audit_resample(path: str, sr_orig: int, sr_new: int) -> dict:
"""
Confirm resampling correctness by checking output frame count and pitch.
Expected output frames = round(input_frames * sr_new / sr_orig).
"""
audio, _sr = sf.read(path, always_2d=True, dtype='float32')
# (N, channels) for soundfile; channels = 1 (mono) or 2 (stereo)
input_frames = audio.shape[0]
expected_frames = int(np.round(input_frames * sr_new / sr_orig))
out_buggy = resample_buggy(audio, sr_orig, sr_new)
out_fixed = resample_fixed(audio, sr_orig, sr_new)
actual_frames_buggy = out_buggy.shape[0]
actual_frames_fixed = out_fixed.shape[0]
# Effective playback speed = actual_sr / tagged_sr
# For buggy: tagged sr_new but actual content is still sr_orig
speed_buggy = sr_orig / sr_new if actual_frames_buggy == input_frames else 1.0
speed_fixed = actual_frames_fixed / expected_frames if expected_frames > 0 else 1.0
# Semitone shift = 12 * log2(speed)
semitones_buggy = 12.0 * np.log2(max(speed_buggy, 1e-6))
semitones_fixed = 12.0 * np.log2(max(speed_fixed, 1e-6))
return {
"shape_in": list(audio.shape),
"shape_buggy": list(out_buggy.shape),
"shape_fixed": list(out_fixed.shape),
"expected_frames": expected_frames,
"frames_buggy": actual_frames_buggy,
"frames_fixed": actual_frames_fixed,
"frames_correct_buggy": actual_frames_buggy == expected_frames,
"frames_correct_fixed": actual_frames_fixed == expected_frames,
"speed_ratio_buggy": round(speed_buggy, 4),
"semitones_buggy": round(semitones_buggy, 2),
"speed_ratio_fixed": round(speed_fixed, 4),
"semitones_fixed": round(semitones_fixed, 2),
}
# --- Axis-safe resampling wrapper for mixed mono/stereo pipelines ---
def resample_safe(audio: np.ndarray, sr_orig: int, sr_new: int,
convention: str = 'soundfile') -> np.ndarray:
"""
Shape-aware resampy wrapper; handles both library conventions.
convention='soundfile': (N, channels) → axis=0
convention='librosa': (channels, N) or (N,) → axis=-1
"""
if sr_orig == sr_new:
return audio
if convention == 'soundfile':
# soundfile.read() returns (N,) mono or (N, channels) stereo
axis = 0
else: # librosa convention: (channels, N) or (N,) mono
axis = -1
return resampy.resample(audio, sr_orig, sr_new, axis=axis,
filter='kaiser_best')
# --- Verify on evaluation set ---
import pathlib
eval_dir = pathlib.Path("/episodes/stereo_48k_eval")
all_correct_buggy = 0
all_correct_fixed = 0
total = 0
for path in sorted(eval_dir.glob("*.wav"))[:20]:
r = audit_resample(str(path), SR_SRC, SR_DST)
total += 1
if r["frames_correct_buggy"]: all_correct_buggy += 1
if r["frames_correct_fixed"]: all_correct_fixed += 1
print(f"{path.name}: "
f"in={r['shape_in']} "
f"buggy={r['shape_buggy']} correct={r['frames_correct_buggy']} "
f"speed={r['speed_ratio_buggy']:.4f} ({r['semitones_buggy']:+.2f} st) "
f"fixed={r['shape_fixed']} correct={r['frames_correct_fixed']} "
f"speed={r['speed_ratio_fixed']:.4f} ({r['semitones_fixed']:+.2f} st)")
print()
print(f"Frame count correct — buggy axis=-1: {all_correct_buggy}/{total}")
print(f"Frame count correct — fixed axis=0: {all_correct_fixed}/{total}")
print()
print("Root cause: resampy.resample(x, sr_orig, sr_new) defaults axis=-1")
print(" For soundfile (N, 2) arrays: axis=-1 = axis 1 (channel axis, length 2)")
print(" Resamples 2-element channel pair, not N-frame time series")
print(" Output (N, 2): same shape, time axis unchanged, audio at sr_orig speed")
print(" File tagged sr_new: plays at sr_orig/sr_new = 1.088x speed, 1.47 st sharp")
print()
print("Fix: resampy.resample(x, sr_orig, sr_new, axis=0)")
print(" Resamples time axis; output (N*sr_new/sr_orig, 2) = (202500, 2)")
print(" Correct playback speed; 1,800 → 0 corrupted episodes/month")
print(" Retainer engagement: 1.5h")
How resampy axis defaults differ between soundfile, librosa, and torchaudio stereo array shapes, and when each convention requires explicit axis specification
The root cause of the Southfield Resampy Ltd. axis error is a mismatch between resampy’s default axis assumption and soundfile’s output convention. resampy defaults to axis=-1 — the last axis — which is correct for 1D mono arrays ((N,), only one axis) and for librosa’s multi-channel convention ((channels, N): last axis is N, the time axis). soundfile’s convention is the opposite: soundfile.read() returns (N,) for mono and (N, channels) for stereo — time is axis 0, channels is axis 1 (the last axis). For stereo soundfile arrays, resampy’s axis=-1 default therefore always targets the channel axis. torchaudio’s convention matches librosa: torchaudio.load() returns (channels, N), so axis=-1 is again the time axis and correct. The safe pattern for a pipeline that uses soundfile is always to specify axis=0 explicitly for 2D arrays. For 1D mono arrays from soundfile ((N,) when no always_2d=True), axis=-1 and axis=0 are equivalent. The only way to silently hit this bug is with a 2D soundfile output — and because soundfile returns 2D for all stereo files unless you explicitly pass always_2d=False and load a mono file, any stereo input will silently trigger the axis error when no explicit axis is provided.
An additional subtlety: because resampy resamples the 2-element channel axis “from sr_orig to sr_new” using its full sinc interpolation filter, and the output has the same 2-element length (since round(2 × 44100/48000) = 2), the returned array passes shape-based checks in downstream code. Checks like assert out.shape[1] == 2 (stereo check) and assert out.dtype == np.float32 all pass. The only reliable quality gate is verifying the output frame count: assert abs(out.shape[0] - round(input_frames * sr_new / sr_orig)) <= 1. For the fixed pipeline, adding this assertion as a post-resample check caught zero failures (all 20 test files had correct output shape) and would have caught all 1,800 month-1 corrupted files had it been in place from the start. The Southfield Resampy Ltd. team added this assertion to the pipeline, switched to axis=0, and added a shape-convention comment in the resampling function: corrupted episodes dropped from 1,800 per month to 0.
Related retainer posts
- pyloudnorm developer on retainer — pyloudnorm 0.1.1; Python 3.9; podcast loudness normalization 5,000 episodes/month; torchaudio (C, T) shape not transposed to (T, C); Meter.integrated_loudness() returns −∞ for all stereo arrays; fix: .numpy().T — 3 weeks
- pyAudioAnalysis developer on retainer — pyAudioAnalysis; Python 3.9; speech/music/noise classification 10,000 segments/day; 24-bit int32 WAV divided by 32768 instead of 8388608; features 48 dB too high; fix: dtype-aware normalization — 3 weeks
- soundfile developer on retainer — soundfile 0.12.1; Python 3.9; broadcast ingest 10,000 files/day; dtype=‘int16’ silently clips inter-sample peaks above 0 dBFS; fix: dtype=‘float64’ + clip + cast — 3 weeks
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 →