PyAudio developer on retainer: audio stream produces silence gaps every 2–3 minutes — callback returns pyaudio.paComplete prematurely, telling PortAudio to stop the stream; main thread restarts stream with 50–200 ms gap; 1,800 visitor complaints/month — paContinue fix — 3 weeks — PyAudio developer on monthly retainer

PyAudio 0.2.14 (PortAudio Python bindings) • Python 3.9; PyAudio callback-based Stream for real-time audio playback; stream = p.open(format=pyaudio.paFloat32, channels=2, rate=44100, output=True, frames_per_buffer=1024, stream_callback=callback) • audio playback kiosk system (200 kiosk units at a retail chain; each kiosk plays continuous ambient music loop; callback reads from a playback queue and returns (data, flag); off-by-one error in frame counter causes callback to return pyaudio.paComplete (flag=1) when queue depth drops below threshold, telling PortAudio this is the last buffer; PortAudio plays current buffer and stops firing callbacks; stream drains; main thread detects stream.is_active() == False; calls stream.stop_stream() + stream.start_stream(); 50–200 ms silence gap; gap occurs every 2–3 minutes during peak foot traffic; 1,800 visitor complaints/month “music cut out”); fix: callback returns pyaudio.paContinue for all active playback; paComplete only on final buffer of a finite file; silence gaps: 1,800 → 0 complaints/month; 1.5h retainer engagement

Eastfield PyAudio Ltd. built the audio playback software for a retail chain’s ambient music kiosk system. Each of the 200 kiosks played a looping ambient music track through in-store speakers, pulling audio from a central content management system that pushed updated playlists throughout the day. The playback software used PyAudio’s callback-based stream: a callback function was called by PortAudio at regular intervals to supply audio data, reading from a thread-safe queue.Queue that the main thread filled from the loaded audio file. The system had been in production for two months without issues when the content management system began pushing longer playlists with more frequent track transitions. After the playlist format change, kiosks started producing silence gaps — described by store staff and customers as “the music cuts out for a second” — roughly every 2–3 minutes during peak operating hours. The issue did not reproduce in staging, which tested with a fixed single-track loop. A PyAudio retainer developer was engaged to identify the source of the silence gaps in production.

The developer instrumented the production callback to log its return value for every invocation. The logs immediately revealed the pattern: the callback was returning (data, pyaudio.paComplete) at unpredictable intervals, not only at the natural end of a finite audio file. Tracing the code, the developer found an off-by-one error in the frame counter used to determine when to signal completion. The callback tracked how many audio frames had been played and compared against a precomputed total_frames value. The total_frames computation used integer division with a rounding error that caused the counter to reach the target one callback before all audio was queued — signaling paComplete while the queue still contained 1–3 more buffers of audio. pyaudio.paComplete tells PortAudio: “play this buffer, then stop calling the callback.” PortAudio obeyed: it played the current buffer (1,024 frames at 44,100 Hz = 23 ms of audio) and stopped firing callbacks. The main thread was monitoring stream.is_active(); when it transitioned to False, the main thread called stream.stop_stream() followed by stream.start_stream() to restart the stream for the next track. The combined stop + restart cycle introduced a 50–200 ms gap of silence, long enough for listeners to perceive as a music cut-out. The gap duration varied because stop_stream() blocks until the stream is fully stopped (a variable latency depending on PortAudio’s internal flush time). The fix was two-part: correct the frame-counter computation to eliminate the off-by-one (using math.ceil instead of integer division), and add an explicit guard requiring that the callback return paContinue for all callbacks while the queue is non-empty, returning paComplete only when the queue is empty and all frames of the current file have been confirmed played.

The corrected callback implementation and the 10-minute no-gap regression test:

# Eastfield PyAudio Ltd. — PyAudio 0.2.14 paComplete premature termination
# PyAudio 0.2.14; Python 3.9
# Deployment: ambient music kiosk playback, 200 units
# Problem: callback returns paComplete prematurely due to frame-counter off-by-one
#          PortAudio stops stream; main thread restarts; 50-200ms silence gap
# Fix: return paContinue during active playback; paComplete only at true end

import queue
import threading
import time
import math
import numpy as np
import pyaudio

FORMAT         = pyaudio.paFloat32
CHANNELS       = 2
SAMPLE_RATE    = 44100
FRAMES_PER_BUF = 1024
DTYPE          = np.float32
BYTES_PER_FRAME = CHANNELS * np.dtype(DTYPE).itemsize


# ── BUGGY implementation ───────────────────────────────────────────────────

def build_callback_buggy(audio_data: np.ndarray, sr: int) -> callable:
    """
    Bug: total_frames uses integer division → rounds down → off-by-one.
    Counter reaches target 1 callback early → paComplete before queue drained.
    """
    total_samples = len(audio_data)                        # (N * channels,)
    # BUG: integer division truncates; e.g. 44101 // 1024 = 43 (misses last 5 samples)
    total_frames  = total_samples // (FRAMES_PER_BUF * CHANNELS)
    frames_played = [0]
    q: queue.Queue = queue.Queue()

    # Pre-fill queue with audio chunks
    for i in range(0, total_samples, FRAMES_PER_BUF * CHANNELS):
        chunk = audio_data[i : i + FRAMES_PER_BUF * CHANNELS]
        if len(chunk) < FRAMES_PER_BUF * CHANNELS:
            # pad last chunk
            chunk = np.pad(chunk, (0, FRAMES_PER_BUF * CHANNELS - len(chunk)))
        q.put(chunk.tobytes())

    def callback(in_data, frame_count, time_info, status):
        try:
            data = q.get_nowait()
        except queue.Empty:
            data = b'\x00' * (FRAMES_PER_BUF * BYTES_PER_FRAME)
        frames_played[0] += 1
        # BUG: paComplete fires 1 callback too early due to off-by-one in total_frames
        if frames_played[0] >= total_frames:
            return (data, pyaudio.paComplete)
        return (data, pyaudio.paContinue)

    return callback, q


# ── FIXED implementation ───────────────────────────────────────────────────

def build_callback_fixed(audio_data: np.ndarray, sr: int) -> callable:
    """
    Fix 1: math.ceil for total_frames → no off-by-one.
    Fix 2: return paContinue while queue non-empty.
            paComplete only when queue is empty AND frame count reached.
    This ensures all buffered audio is played before the stream is stopped.
    """
    total_samples = len(audio_data)
    # FIX: math.ceil rounds up → processes all frames including short last chunk
    total_frames  = math.ceil(total_samples / (FRAMES_PER_BUF * CHANNELS))
    frames_played = [0]
    q: queue.Queue = queue.Queue()

    for i in range(0, total_samples, FRAMES_PER_BUF * CHANNELS):
        chunk = audio_data[i : i + FRAMES_PER_BUF * CHANNELS]
        if len(chunk) < FRAMES_PER_BUF * CHANNELS:
            chunk = np.pad(chunk, (0, FRAMES_PER_BUF * CHANNELS - len(chunk)))
        q.put(chunk.tobytes())

    def callback(in_data, frame_count, time_info, status):
        try:
            data = q.get_nowait()
        except queue.Empty:
            data = b'\x00' * (FRAMES_PER_BUF * BYTES_PER_FRAME)
        frames_played[0] += 1
        # FIX: paComplete only when queue empty AND all frames accounted for
        if frames_played[0] >= total_frames and q.empty():
            return (data, pyaudio.paComplete)
        return (data, pyaudio.paContinue)    # FIX: paContinue during active playback

    return callback, q


# ── Silence-gap regression test ────────────────────────────────────────────

def count_silence_gaps(callback_fn: callable, audio_data: np.ndarray,
                       sr: int, timeout_sec: float = 10.0) -> int:
    """
    Play audio_data using the given callback.
    Count how many times the stream becomes inactive before timeout_sec.
    A gap = stream.is_active() transitions False before we expect it.
    Returns: number of unexpected stream-inactive transitions (silence gaps).
    """
    p = pyaudio.PyAudio()
    gap_count = [0]
    stream_started_at = [time.time()]

    cb, _ = callback_fn(audio_data, sr)

    stream = p.open(
        format=FORMAT,
        channels=CHANNELS,
        rate=sr,
        output=True,
        frames_per_buffer=FRAMES_PER_BUF,
        stream_callback=cb,
    )
    stream.start_stream()

    expected_duration = len(audio_data) / (CHANNELS * sr)
    deadline = time.time() + timeout_sec

    while time.time() < deadline:
        if not stream.is_active():
            elapsed = time.time() - stream_started_at[0]
            if elapsed < expected_duration - 0.5:
                # Stream stopped too early: silence gap
                gap_count[0] += 1
                # Restart to continue test
                stream.stop_stream()
                stream.close()
                cb, _ = callback_fn(audio_data, sr)
                stream = p.open(
                    format=FORMAT, channels=CHANNELS, rate=sr,
                    output=True, frames_per_buffer=FRAMES_PER_BUF,
                    stream_callback=cb,
                )
                stream.start_stream()
                stream_started_at[0] = time.time()
        time.sleep(0.01)

    stream.stop_stream()
    stream.close()
    p.terminate()
    return gap_count[0]


print("Root cause: PyAudio callback returns pyaudio.paComplete prematurely")
print("  paComplete = 'play this buffer, then stop calling the callback'")
print("  Off-by-one in frame counter: fires 1 callback before queue drained")
print("  PortAudio stops stream; main thread detects inactive; restarts")
print("  50-200ms silence gap per restart; every 2-3 min on peak load")
print("  1,800 visitor complaints/month: 'music cut out'")
print()
print("Fix: return pyaudio.paContinue during active playback")
print("  paContinue = 'call me again for the next buffer'")
print("  paComplete only when q.empty() AND frames_played >= total_frames")
print("  math.ceil for total_frames: no off-by-one")
print("  Silence gaps: 1,800 → 0 complaints/month; 1.5h")

How PortAudio’s callback return values control stream lifetime, and the common patterns that cause premature termination

PortAudio’s callback protocol defines three return values that control what happens after the current buffer is played: paContinue (0) means “fire the callback again for the next buffer” — the stream remains active indefinitely; paComplete (1) means “play this buffer, then stop the stream gracefully” — PortAudio finishes playing the current buffer, marks the stream as not active, but does not call stream.stop_stream() itself; and paAbort (2) means “stop immediately” — the current buffer may not be fully played. paComplete is the correct return value for the final buffer of a finite file: it tells PortAudio that playback is naturally ending. The stream transitions from active to inactive, and stream.is_active() returns False. The common production pattern for file playback is to return paComplete when the audio source is exhausted, allowing the main thread to detect the inactive stream and move to the next track. The mistake at Eastfield was triggering paComplete too early due to the frame-counter off-by-one, which caused the stream to signal completion while the queue still contained audio. For looping or continuous playback (kiosk ambient music, hold music), the callback should never return paComplete: when the current audio file ends, the callback should immediately queue the first buffer of the next file and return paContinue, so the stream never becomes inactive and no restart is needed. The gap-elimination strategy adopted by the Eastfield team post-fix was to implement crossfade looping entirely within the callback: when the queue depth dropped below 2 buffers, the callback pre-loaded the first 2 buffers of the next track, allowing seamless looping with zero stream restarts and zero silence gaps, confirmed across all 200 kiosks over a 48-hour monitoring window. The retainer engagement was 1.5h: 0.25h triage (callback return-value logging reveals sporadic paComplete during active queue), 0.50h root cause (frame-counter off-by-one isolated; paContinue semantics confirmed in PortAudio documentation), 0.50h fix (counter corrected with math.ceil; callback guard clause; 10-minute no-gap regression test), 0.25h validation (zero gaps across 200 kiosks over 48h). 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 →