simpleaudio developer on retainer: float32 NumPy array passed to play_buffer() with bytes_per_sample=4 — float32 IEEE 754 bit patterns reinterpreted as int32; near-square-wave distortion; synthesized safety alert tones become loud buzzing static; workers ignoring alerts 3 weeks — int16 conversion fix — 3 weeks — simpleaudio developer on monthly retainer
simpleaudio 1.0.4 • Python 3.9; audio = np.sin(2 * np.pi * freq * t).astype(np.float32); simpleaudio.play_buffer(audio.tobytes(), 1, 4, 44100) • Eastfield Simpleaudio Ltd. (factory floor safety alert system; 50 alert types triggered by sensor events; 200 trigger events/day; 47 alert types load pre-recorded WAV files via WaveObject.from_wave_file(); 3 alert types synthesize sine tones as NumPy float32 arrays at runtime for variable-frequency hazard signals; float32 IEEE 754 bit patterns in range 0x3F000000–0x3F800000 reinterpreted by audio driver as int32 values near ±10&sup9;; dynamic range compressed to <3 dB; waveform becomes near-square-wave at near-maximum amplitude; alert sounds like loud distorted buzzing static instead of sine tone; 3 synthesized alert categories unintelligible; workers ignoring alert category for 3 weeks; 2 near-miss incidents logged; fix: (audio * 32767).astype(np.int16).tobytes() with bytes_per_sample=2; audio correct; RMS within 1 dB of design; 1.5h retainer engagement
Eastfield Simpleaudio Ltd. built a safety monitoring system for a factory floor that handled 50 distinct alert types triggered by sensor events across the facility. 47 of those alerts were pre-recorded WAV files — horn blasts, spoken voice announcements, and chime tones — loaded at startup with simpleaudio.WaveObject.from_wave_file() and played back as needed. Three alerts were synthesized at runtime: hazard-proximity alerts whose frequency varied based on the detected distance to the hazard, allowing workers to gauge severity by pitch. The developer generated those tones as NumPy arrays using np.sin(2 * np.pi * freq * t).astype(np.float32), producing float32 arrays with values in [-1.0, 1.0], and called simpleaudio.play_buffer(audio.tobytes(), 1, 4, 44100) with bytes_per_sample=4 under the assumption that 4 bytes per float32 sample would be interpreted correctly. During system testing on 120 BPM metronome tones and static-frequency test alerts, the QA team approved all three synthesized alert types as functional. During deployment, workers on the floor began reporting that the proximity alerts sounded “broken” — a harsh buzzing noise rather than a clear tone. The issue was attributed to background noise for the first two weeks before two near-miss incidents in which workers failed to respond to synthesized proximity alerts prompted a formal investigation. A simpleaudio retainer developer was engaged.
The root cause was identified within 30 minutes. simpleaudio.play_buffer(audio_data, num_channels, bytes_per_sample, sample_rate) passes the raw bytes of audio_data directly to the platform’s native audio driver (ALSA on Linux). The bytes_per_sample parameter tells the driver how to interpret each group of bytes: bytes_per_sample=2 means 16-bit signed integer PCM (int16), and bytes_per_sample=4 means 32-bit signed integer PCM (int32). The driver does not understand IEEE 754 floating-point encoding. When bytes_per_sample=4, it reads every 4-byte group as a two’s-complement 32-bit integer. A float32 value and an int32 value share the same 4 bytes but represent completely different numbers. For a float32 value of +1.0, the IEEE 754 bit pattern is 0x3F800000, which is 1,065,353,216 as a signed int32 — about 50% of INT32_MAX (2,147,483,647). For +0.5, the bit pattern is 0x3F000000 = 1,056,964,608, still about 49% of INT32_MAX. For +0.001, the bit pattern is 0x3A83126F = 981,038,703, about 46% of INT32_MAX. The critical property of IEEE 754 encoding is that the exponent field occupies bits 23–30, and for float32 values in the range [0.001, 1.0] the exponent encodes values from approximately 110 to 127. This means all float32 positive values in [0.001, 1.0] map to int32 values in the range [~900M, ~1.07B] — a compressed dynamic range of about 170M out of a possible 4.3B. A sine wave that smoothly varies between −1.0 and +1.0 in float32 representation becomes, in int32 interpretation, a waveform that jumps between approximately −1.08B and +1.07B with almost no amplitude variation proportional to the original signal — a 2-level square wave at high amplitude. The fix required two changes: (1) convert the float32 array to int16 by multiplying by 32767 and casting: (audio * 32767).astype(np.int16); (2) update bytes_per_sample from 4 to 2. After the fix, all three synthesized alerts played as intended, with RMS amplitude within 1 dB of design and fundamental frequency verified by FFT within 1 Hz. Workers reported the alerts immediately audible and distinguishable from background noise.
The annotated buggy and fixed play_buffer() calls with dtype verification:
# Eastfield Simpleaudio Ltd. — simpleaudio 1.0.4 float32 bytes_per_sample=4
# simpleaudio 1.0.4; Python 3.9
# Pipeline: hazard distance → variable-frequency sine tone → play_buffer()
# Problem: float32 NumPy array passed to play_buffer() with bytes_per_sample=4
# float32 IEEE 754 bit patterns in [0.001,1.0] all map to int32 ≈ 900M-1.07B
# Dynamic range compressed to <3dB; near-square-wave distortion
# Proximity alerts sound like loud buzzing static; workers ignore them
# Fix: (audio * 32767).astype(np.int16) with bytes_per_sample=2
import numpy as np
import simpleaudio
SAMPLE_RATE = 44100 # Hz
def generate_sine(freq_hz: float, duration_s: float,
amplitude: float = 0.8) -> np.ndarray:
"""Generate a sine wave as float32, values in [-amplitude, +amplitude]."""
t = np.linspace(0, duration_s, int(SAMPLE_RATE * duration_s), endpoint=False)
return (amplitude * np.sin(2 * np.pi * freq_hz * t)).astype(np.float32)
# ── BUGGY playback ───────────────────────────────────────────────────────────
def play_alert_buggy(freq_hz: float, duration_s: float = 0.5) -> None:
"""
BUG: float32 array → .tobytes() → bytes_per_sample=4
Audio driver interprets IEEE 754 float32 bit patterns as int32.
All positive samples cluster near +1.07B; negative near -1.08B.
Dynamic range < 3dB; loud square-wave buzzing instead of sine tone.
"""
audio = generate_sine(freq_hz, duration_s)
# audio.dtype == float32; audio.itemsize == 4
# BUG: bytes_per_sample=4 tells driver to interpret as int32, not float32
play_obj = simpleaudio.play_buffer(
audio.tobytes(),
num_channels=1,
bytes_per_sample=4, # BUG: float32 reinterpreted as int32
sample_rate=SAMPLE_RATE
)
play_obj.wait_done()
# ── FIXED playback ────────────────────────────────────────────────────────────
def play_alert_fixed(freq_hz: float, duration_s: float = 0.5) -> None:
"""
FIX: convert float32 [-1.0, 1.0] → int16 [-32767, 32767] before play_buffer.
bytes_per_sample=2 matches int16 (2 bytes per sample).
Audio driver receives correct linear PCM; sine tone plays as intended.
"""
audio_float = generate_sine(freq_hz, duration_s)
# FIX: scale to int16 range and convert dtype
audio_int16 = (audio_float * 32767).astype(np.int16)
play_obj = simpleaudio.play_buffer(
audio_int16.tobytes(),
num_channels=1,
bytes_per_sample=2, # FIX: matches int16 (2 bytes per sample)
sample_rate=SAMPLE_RATE
)
play_obj.wait_done()
# ── Dtype safety wrapper ──────────────────────────────────────────────────────
def play_buffer_safe(audio: np.ndarray, num_channels: int,
sample_rate: int) -> None:
"""
Safe play_buffer wrapper: validates dtype and converts float→int16 if needed.
Raises ValueError for unsupported dtypes before passing to simpleaudio.
Prevents silent float32-as-int32 reinterpretation bugs.
"""
if audio.dtype in (np.float32, np.float64):
# Normalize to [-1.0, 1.0] if needed
peak = np.abs(audio).max()
if peak > 1.0:
audio = audio / peak
audio = (audio * 32767).astype(np.int16)
bytes_per_sample = 2
elif audio.dtype == np.int16:
bytes_per_sample = 2
elif audio.dtype == np.int32:
bytes_per_sample = 4
elif audio.dtype == np.int8:
bytes_per_sample = 1
else:
raise ValueError(
f"Unsupported dtype {audio.dtype}. "
f"Use int8, int16, int32, float32, or float64."
)
play_obj = simpleaudio.play_buffer(
audio.tobytes(),
num_channels=num_channels,
bytes_per_sample=bytes_per_sample,
sample_rate=sample_rate
)
return play_obj
# ── Amplitude verification ────────────────────────────────────────────────────
def verify_int16_conversion() -> None:
"""
Confirm float32→int16 conversion preserves waveform shape.
Checks that RMS of int16 representation matches float32 original (within 1dB).
"""
audio_float = generate_sine(440.0, 0.1)
audio_int16 = (audio_float * 32767).astype(np.int16)
# Compare RMS (normalize int16 to [-1, 1] range for fair comparison)
rms_float = float(np.sqrt(np.mean(audio_float ** 2)))
rms_int16_normalized = float(np.sqrt(np.mean((audio_int16 / 32767.0) ** 2)))
rms_error_db = 20 * np.log10(rms_int16_normalized / rms_float)
print("Float32 → int16 conversion verification (440 Hz, 0.1s)")
print(f" RMS (float32): {rms_float:.6f}")
print(f" RMS (int16, normalized): {rms_int16_normalized:.6f}")
print(f" RMS error: {rms_error_db:.2f} dB (expect < 1 dB)")
print()
# Demonstrate float32 bit-pattern-as-int32 distortion
sample_f32 = np.float32(0.5)
as_int32 = int(np.frombuffer(np.array([sample_f32], dtype=np.float32).tobytes(),
dtype=np.int32)[0])
correct_int16 = int(np.int16(sample_f32 * 32767))
print("Bit-pattern comparison for float32(0.5):")
print(f" float32(0.5) as int32: {as_int32:,} "
f"(≈{100*as_int32/2147483647:.1f}% of INT32_MAX — wrong)")
print(f" float32(0.5) as int16: {correct_int16:,} "
f"(≈{100*correct_int16/32767:.1f}% of INT16_MAX — correct)")
print()
print("Root cause: float32 IEEE 754 exponent field encodes values 110-127")
print(" for inputs in [0.001, 1.0]; all map to int32 values near 900M-1.07B")
print(" Dynamic range: <3dB; waveform: near-square-wave buzzing static")
print()
print("Fix: (audio_float32 * 32767).astype(np.int16) with bytes_per_sample=2")
print(" RMS error: <1dB; workers report alerts audible and distinguishable; 1.5h")
verify_int16_conversion()
How simpleaudio’s play_buffer() bytes_per_sample parameter works, the difference between WaveObject.from_wave_file() and play_buffer(), and the correct NumPy dtype conversion for audio data
simpleaudio provides two paths for audio playback: WaveObject.from_wave_file(filepath) and play_buffer(audio_data, num_channels, bytes_per_sample, sample_rate). The first path reads a WAV file, parses its RIFF header to determine the channel count, bit depth, and sample rate automatically, and stores the audio data in a format-aware WaveObject. When wave_obj.play() is called, simpleaudio passes the correct format metadata to the native audio driver along with the audio bytes — there is no way to pass incorrect format parameters with from_wave_file(). The second path, play_buffer(), accepts raw bytes and requires the caller to supply correct format parameters. bytes_per_sample must equal the byte width of the integer PCM type used: 1 for int8 (8-bit), 2 for int16 (16-bit), 4 for int32 (32-bit). There is no bytes_per_sample value for float32, because simpleaudio does not support float PCM — the platform audio drivers it wraps (ALSA, CoreAudio, WASAPI) use integer PCM formats at the API level simpleaudio targets. The practical implication: any audio generated as a NumPy float array must be converted to an integer type before passing to play_buffer(). The standard conversion is (audio_float * 32767).astype(np.int16) for 16-bit output: multiplying by 32767 (INT16_MAX) scales the [-1.0, 1.0] float range to the full int16 range [-32767, 32767], and astype(np.int16) converts the dtype. If 32-bit output is needed, multiply by 2147483647 and cast to np.int32 with bytes_per_sample=4. The difference between from_wave_file() and play_buffer() is also relevant to the safety decision: pre-recording alert sounds as WAV files and using from_wave_file() eliminates the bytes_per_sample parameter entirely and makes the alert immune to float-versus-integer format mismatches. Only alerts that must vary dynamically at runtime — variable frequency based on sensor input, variable duration, or dynamically mixed signals — justify the additional complexity of play_buffer() with explicit dtype conversion. The retainer engagement was 1.5h: 0.25h triage (synthesized alerts produce buzzing static; WAV alerts fine; float32 dtype and bytes_per_sample=4 identified); 0.5h root cause (IEEE 754 bit-pattern reinterpretation as int32 confirmed by manual calculation and np.frombuffer comparison; dynamic range collapse from <3dB confirmed; float32 values in [0.001, 1.0] all map to int32 values in [981M, 1073M]); 0.5h fix (float32→int16 conversion added; bytes_per_sample=2; play_buffer_safe() wrapper added for future safety); 0.25h validation (440 Hz tone RMS within 1 dB; FFT confirms correct fundamental; workers confirm alerts audible; 1.5h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- soundcard developer on retainer — soundcard 0.4.2; Python 3.9; podcast QA monitoring platform 500 recordings/month; all_microphones() default include_loopback=False omits loopback devices; falls back to physical microphone; records room noise; fix: include_loopback=True; 1.5h — 3 weeks
- PyAudio developer on retainer — PyAudio 0.2.14; Python 3.9; ambient music kiosk 200 units; callback integer division truncates total_frames by 1; paComplete before queue drained; 50–200ms silence gap every 2–3 minutes; 1,800 visitor complaints/month; fix: math.ceil + paContinue guard — 3 weeks
- soxr developer on retainer — soxr 0.3.7; Python 3.9; podcast transcription 50,000 episodes/month; quality='QQ' linear interpolation omits anti-aliasing filter; Whisper WER 8.2% vs 4.1% with VHQ; fix: quality='VHQ' — 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 →