miniaudio developer on retainer: PlaybackDevice SIGNED16 receives float32 generator bytes — IEEE 754 float bit patterns interpreted as int16 — audio plays as loud distorted noise — volume control has no effect — 2.5 weeks — miniaudio developer on monthly retainer
miniaudio 1.57 • Python 3.10; PlaybackDevice(output_format=SampleFormat.SIGNED16); generator yields float32 array .tobytes(); miniaudio expects int16 bytes for SIGNED16; float32 bit patterns (0.3 = 0x3E99999A) interpreted as two int16 values (−26214 and 15897); audio plays as full-scale broadband noise; fix: (samples * 32767).clip(−32768, 32767).astype(np.int16).tobytes() • Southfield Miniaudio Ltd. (game audio engine; 10,000 sound effects library; 2.5 weeks; 2.0h retainer engagement)
Southfield Miniaudio Ltd. built a game audio engine processing 10,000 sound effects for a real-time strategy game. The audio pipeline generated procedural variations of each sound effect using NumPy synthesis: frequency-shifted explosions, pitch-randomized footsteps, spatially-panned ambient sounds. Each sound was synthesized as a float32 NumPy array with values in [−1.0, 1.0], then fed to miniaudio (1.57) for real-time playback. The developer, familiar with sounddevice’s callback API (which natively accepts float32 arrays), wrote the miniaudio generator to yield samples.tobytes() where samples was a float32 NumPy array. The PlaybackDevice was configured as miniaudio.PlaybackDevice(output_format=miniaudio.SampleFormat.SIGNED16, nchannels=2, sample_rate=44100). miniaudio’s SampleFormat.SIGNED16 expects generators to yield bytes containing interleaved int16 samples (2 bytes per sample, range −32768 to 32767). The generator was yielding float32 bytes instead (4 bytes per sample, IEEE 754). miniaudio performs no format conversion: it passes the generator’s bytes directly to the hardware audio buffer. The hardware interpreted each pair of bytes as one int16 value. All 10,000 sound effects played as loud broadband noise with no resemblance to the intended audio.
The core mechanism: a float32 value of 0.3 is stored in IEEE 754 as 0x3E99999A — four bytes: 0x9A, 0x99, 0x99, 0x3E. When the hardware interprets these four bytes as two int16 values in little-endian order: int16(0x999A) = −26214 and int16(0x3E99) = 15897. These are 80% and 48% of int16’s full scale, respectively — near-maximum amplitude for a signal intended to play at 30% volume. For any typical audio sample in [−0.5, 0.5], the IEEE 754 exponent bits are always in the range 0x3E–0x3F (roughly 0.5–1.0 as a 2-byte int16 segment), producing near-maximum amplitude values regardless of the intended float scale. The resulting audio is dominated by the high-frequency noise from rapidly-changing bit patterns. Volume control applied to the float values (multiply by 0.1 for 10% volume) only changes the mantissa bits, not the exponent bits: a float32 value of 0.03 (0x3CF5C28F) still produces int16 values int16(0xC28F) = −15729 and int16(0x3CF5) = 15605 — still near-maximum. Volume control had no effect on the noise level. The 2.5-week investigation covered audio driver settings, OS mixer configuration, miniaudio build options, and Python NumPy version combinations, none of which addressed the byte-format mismatch. The diagnostic that isolated the bug was printing the first 8 bytes of the generator output and comparing them against manually-computed int16 bytes for a 440 Hz sine wave at 10% amplitude.
The annotated buggy and fixed generator, with format validation and amplitude guard:
# Southfield Miniaudio Ltd. — miniaudio 1.57 SIGNED16 format fix
# miniaudio 1.57; Python 3.10; NumPy 1.24
# Game audio engine; 10,000 sound effects; 2.5 weeks; 2.0h retainer
#
# Problem: PlaybackDevice(output_format=SampleFormat.SIGNED16) expects int16 bytes
# Generator yielded float32 array .tobytes() instead
# IEEE 754 float bit patterns interpreted as int16 by hardware
# float32(0.3) = 0x3E99999A → int16(-26214) and int16(15897) [near-max]
# Audio plays as full-scale broadband noise for all 10,000 effects
# Volume control (multiply float by scalar) has no effect on noise level
# Fix: Convert float32 to int16 before yielding bytes
import miniaudio
import numpy as np
import math
SAMPLE_RATE = 44100
CHANNELS = 2
CHUNK_SAMPLES = 2048 # samples per channel per generator yield
# ── BUGGY audio generator ─────────────────────────────────────────────────────
def synthesize_effect_buggy(frequency_hz: float, duration_s: float):
"""BUGGY: yields float32 bytes to a SIGNED16 PlaybackDevice."""
n_samples = int(SAMPLE_RATE * duration_s)
t = np.linspace(0, duration_s, n_samples, endpoint=False, dtype=np.float32)
left = np.sin(2 * np.pi * frequency_hz * t) * 0.5
right = left * 0.9 # slight pan
# Stereo interleave: (n_samples, 2) → (n_samples * 2,)
stereo = np.column_stack([left, right]).flatten()
# BUG: .tobytes() on a float32 array yields 4 bytes per value (IEEE 754)
# PlaybackDevice SIGNED16 expects 2 bytes per value (int16)
# Hardware interprets float32 bit patterns as pairs of int16 values
# 0.5 float32 = 0x3F000000 → int16(0x0000)=0, int16(0x3F00)=16128
for i in range(0, len(stereo), CHUNK_SAMPLES * CHANNELS):
chunk = stereo[i : i + CHUNK_SAMPLES * CHANNELS]
yield chunk.tobytes() # BUG: float32 bytes, not int16 bytes
# ── FIXED audio generator ─────────────────────────────────────────────────────
def float32_to_signed16_bytes(samples_float32: np.ndarray) -> bytes:
"""
Convert float32 audio samples in [-1.0, 1.0] to int16 bytes.
.clip() prevents overflow wrapping when samples exceed [-1.0, 1.0].
"""
samples_int16 = (samples_float32 * 32767.0).clip(-32768, 32767).astype(np.int16)
return samples_int16.tobytes()
def synthesize_effect(frequency_hz: float, duration_s: float, volume: float = 1.0):
"""FIXED: converts float32 to int16 before yielding bytes."""
assert 0.0 <= volume <= 1.0, f"Volume must be in [0.0, 1.0], got {volume}"
n_samples = int(SAMPLE_RATE * duration_s)
t = np.linspace(0, duration_s, n_samples, endpoint=False, dtype=np.float64)
left = np.sin(2 * np.pi * frequency_hz * t) * 0.5 * volume
right = left * 0.9
# Keep in float64 for mixing precision; convert to float32 at yield
stereo = np.column_stack([left, right]).flatten().astype(np.float32)
for i in range(0, len(stereo), CHUNK_SAMPLES * CHANNELS):
chunk = stereo[i : i + CHUNK_SAMPLES * CHANNELS]
# Correct: float32 → int16 → bytes
yield float32_to_signed16_bytes(chunk)
# ── Startup format validation ─────────────────────────────────────────────────
def validate_generator_format(generator_fn, device_format: miniaudio.SampleFormat) -> None:
"""
Validate that a generator yields bytes matching the device format.
Call once at engine startup before attaching to PlaybackDevice.
For SampleFormat.SIGNED16: each sample = 2 bytes.
For SampleFormat.FLOAT32: each sample = 4 bytes.
"""
format_bytes = {
miniaudio.SampleFormat.SIGNED16: 2,
miniaudio.SampleFormat.FLOAT32: 4,
miniaudio.SampleFormat.UNSIGNED8: 1,
miniaudio.SampleFormat.SIGNED32: 4,
}
bytes_per_sample = format_bytes[device_format]
# Pull first chunk from generator
gen = generator_fn(440.0, 0.1) # 100ms 440 Hz test tone
first_chunk = next(gen)
total_bytes = len(first_chunk)
samples_per_chunk = total_bytes / bytes_per_sample
if total_bytes % bytes_per_sample != 0:
raise ValueError(
f"Generator yielded {total_bytes} bytes, which is not divisible by "
f"{bytes_per_sample} bytes/sample for {device_format}. "
f"This usually means the generator is yielding float32 bytes "
f"(.tobytes() on dtype=float32) for a SIGNED16 device — "
f"fix: (samples * 32767).astype(np.int16).tobytes()"
)
# For SIGNED16: check that values are plausible int16 (not float32 bit patterns)
if device_format == miniaudio.SampleFormat.SIGNED16:
samples_int16 = np.frombuffer(first_chunk, dtype=np.int16)
rms = np.sqrt(np.mean(samples_int16.astype(np.float64) ** 2))
# A correctly generated 440 Hz tone at 50% volume (0.5 * 32767 ≈ 16384)
# should have RMS around 11585 (= 16384 / sqrt(2))
# Float32 bytes interpreted as int16 produce near-max RMS (20000+)
if rms > 25000:
raise ValueError(
f"Generator RMS for SIGNED16 device is {rms:.0f} (expected ~11585 "
f"for a 50%-volume 440 Hz tone). This suggests the generator is "
f"yielding float32 bytes instead of int16 bytes. "
f"Fix: (samples * 32767).clip(-32768, 32767).astype(np.int16).tobytes()"
)
print(
f"[miniaudio startup OK] Generator format validated for {device_format}: "
f"{total_bytes} bytes/chunk = {samples_per_chunk:.0f} samples/chunk. "
f"RMS: {rms:.0f} (expected ~11585 for 50%-volume tone)."
)
# ── PlaybackDevice setup (correct) ───────────────────────────────────────────
def build_playback_device(generator_fn) -> miniaudio.PlaybackDevice:
validate_generator_format(generator_fn, miniaudio.SampleFormat.SIGNED16)
device = miniaudio.PlaybackDevice(
output_format=miniaudio.SampleFormat.SIGNED16,
nchannels=CHANNELS,
sample_rate=SAMPLE_RATE,
buffersize_msec=200,
)
return device
Why PlaybackDevice SIGNED16 produces full-scale noise from float32 generator bytes — and why the volume slider has no effect on the noise level
The failure combines three factors. First, miniaudio’s PlaybackDevice performs no implicit format conversion between the generator’s output and the device’s configured SampleFormat. This design is intentional: format conversion adds latency and miniaudio targets real-time applications where the developer is expected to produce correctly-formatted bytes. The documentation specifies this, but developers coming from sounddevice (which natively accepts float32 NumPy arrays in its callback and performs conversion internally) or pygame.mixer (which accepts Sound objects from an array and handles conversion) expect implicit conversion as the default. Second, calling .tobytes() on a float32 NumPy array produces valid bytes in the sense that no exception is raised and the byte count is non-zero — the error is entirely silent. miniaudio feeds those bytes to the hardware without inspection. The hardware’s behavior is defined (interpret each 2-byte pair as int16) so no crash or warning occurs at the hardware level either. Third, the mathematical structure of IEEE 754 float32 means that typical audio values (in [−1.0, 1.0]) produce near-maximum int16 values when their byte representations are reinterpreted: for any normalized float in [0.5, 1.0], the exponent byte is 0x3F, which as a signed 16-bit segment is 16128 — 49% of the int16 maximum (32767). The mantissa bytes follow no pattern audible as the original signal. Volume control (scaling the float values) only changes the mantissa bits and sometimes the low exponent bits, but for volumes above ~0.03 the exponent byte remains 0x3D–0x3F, producing near-maximum int16 values in all cases. Only below ~0.001 (3 orders of magnitude quieter than the intended level) do the float values become subnormal, producing int16 values near zero. Southfield Miniaudio Ltd.’s volume slider operated in the range 0.0–1.0, and all values in that range produced near-maximum noise. The fix adds two operations before .tobytes(): scale to int16 range (* 32767.0) and convert dtype (.astype(np.int16)). The .clip(−32768, 32767) guard prevents integer overflow wrapping when mixing multiple sources causes samples to transiently exceed [−1.0, 1.0]. The retainer engagement was 2.0h: 0.25h triage (compare first 8 generator bytes against expected 440 Hz sine bytes at 50% volume; byte values confirm float32 bit patterns, not int16); 0.5h root cause (SIGNED16 expects int16 bytes; sounddevice performs implicit conversion but miniaudio does not; float32 IEEE 754 exponent bits produce near-maximum int16 reinterpretations); 0.75h fix (float32-to-int16 conversion; clip guard; startup RMS validator); 0.5h validation (10,000 effects sample; audio matches intended frequency and amplitude; volume slider operational; 2.0h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- pyaudio developer on retainer — PyAudio 0.2.13; Python 3.10;
stream.write()receives float32 bytes forformat=pyaudio.paInt16; garbled audio; fix:(data * 32767).astype(np.int16).tobytes(); 1.5h - sounddevice developer on retainer — sounddevice 0.4.6; Python 3.10;
callbackoutput buffer assigned float64 array instead of float32; PortAudio receives 8-byte samples in a 4-byte buffer; audio noise; fix:.astype(np.float32)before assignment; 1.5h - pydub developer on retainer — pydub 0.25.1; Python 3.10;
AudioSegment.detect_nonsilent()min_silence_lenin milliseconds;silence_threshin dBFS relative to full scale; threshold set as absolute value instead of relative; fix:audio.dBFS - 16; 2.0h
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 →