pydub developer on retainer: split_on_silence keep_silence double-padding produces 400ms silence at every segment boundary — keep_silence retains trailing silence from prior segment AND leading silence from current segment — keep_silence=False + manual slice fix — 3 weeks — pydub developer on monthly retainer

pydub (jiaaro/pydub) 0.25.1 • Python 3.9; high-level audio manipulation library providing AudioSegment slicing, concatenation, format conversion, loudness normalization, and silence detection via FFmpeg subprocess; split_on_silence() returns non-silence segments with optional silence padding controlled by keep_silence parameter • podcast transcription pre-processing pipeline (2,000 episodes/month: split episodes into utterance-level segments before submitting to Whisper API; target: 50–80 segments per 45-minute episode; silence_thresh=−40 dBFS, min_silence_len=500ms, keep_silence=200ms); 400ms double-silence padding at every segment boundary — Whisper API WER increases 3.2 percentage points (8.2% → 11.4%) on affected segments; word timestamp offset ±200ms • developer investigates pydub split_on_silence keep_silence implementation, silence interval boundary slicing, and downstream Whisper WER sensitivity to inter-segment padding for 3 weeks • root cause: split_on_silence(keep_silence=200) appends 200ms from the start of each silence interval to the end of the preceding segment AND prepends 200ms from the end of each silence interval to the beginning of the following segment; when concatenated for downstream processing, segments have 200ms trailing silence + 200ms leading silence = 400ms at every boundary; Whisper interprets 400ms inter-segment silence as an in-utterance pause, inserting spurious tokens and misplacing word timestamps by ±200ms • fix: keep_silence=False + segment[silence_ms:] manual trim on each segment; WER: 8.1% across all segments; timestamp error: <±30ms; 1.5h retainer engagement

Southfield Pydub Ltd. had built a podcast transcription pre-processing pipeline that segmented 2,000 podcast episodes per month into utterance-level chunks before submitting each chunk to the Whisper API. The pipeline used pydub 0.25.1’s split_on_silence() with silence_thresh=-40 (dBFS), min_silence_len=500 (ms), and keep_silence=200 (ms). The keep_silence=200 setting was chosen to avoid abrupt word-boundary cuts — the standard guidance in pydub documentation is to add a small silence buffer to prevent the first and last words of each segment from being clipped. For the initial batch of 500 English monologue episodes from a fixed studio microphone, the pipeline produced 52–78 segments per episode and achieved Whisper WER of 8.2% on a 50-episode held-out evaluation set. After expanding to 2,000 episodes per month including interview podcasts with longer natural pauses (1–3 seconds between speaker turns), Whisper WER on the production pipeline climbed to 11.4%. Analysis of Whisper’s word-level timestamps revealed that the timestamps for the first 1–3 words of each segment were offset by approximately 200ms, and that Whisper was intermittently inserting “Hmm”, “Um”, and other filler tokens at segment boundaries. The team initially attributed this to Whisper’s hallucination behavior on silence, but the offset was too regular — exactly 200ms — to be random. A pydub retainer developer was engaged to investigate whether the keep_silence parameter was interacting with Whisper’s behavior in an unexpected way.

The developer’s investigation began by measuring the actual silence content at segment boundaries in the split output. For a sample episode with a 1.2-second pause between host and guest at the 3-minute mark, the developer examined the last 500ms of the segment ending at that pause and the first 500ms of the segment starting after it. Both segments contained exactly 200ms of silence at their respective boundaries — the last 200ms of the first segment and the first 200ms of the second segment were flat silence waveform. This confirmed that keep_silence was operating as documented: 200ms of silence was being added to each segment end. However, the developer identified the downstream interaction: when the pipeline serialized segments to WAV files and submitted them sequentially to Whisper, the concatenated boundary at the join point contained 200ms of trailing silence from segment N followed immediately by 200ms of leading silence from segment N+1 — 400ms total. For Whisper, 400ms of silence within a submission batch is interpreted as a natural within-utterance pause, causing the model to expect continuation speech and to place the first token of segment N+1’s content approximately 200ms later in its internal timeline than the actual audio. The fix was to use keep_silence=False (which returns segments without any silence padding) and manually trim the first silence_ms samples from each segment to remove any residual noise at the cut point, using a simple amplitude-envelope check to determine how much leading silence to trim. Whisper WER dropped from 11.4% to 8.1% across the full evaluation set, and word timestamp error fell from ±200ms to below ±30ms.

The diagnostic code that confirmed the double-padding mechanism and the corrected segmentation implementation:

# Southfield Pydub Ltd. — pydub 0.25.1 split_on_silence keep_silence double-padding diagnostic
# pydub (jiaaro/pydub) 0.25.1; Python 3.9
# Deployment: podcast transcription pre-processing, 2,000 episodes/month
# Problem: keep_silence=200 produces 400ms double-silence at segment boundaries
# Fix: keep_silence=False + manual trim

import numpy as np
from pydub import AudioSegment
from pydub.silence import split_on_silence, detect_silence

SILENCE_THRESH_DBFS = -40
MIN_SILENCE_LEN_MS  = 500
KEEP_SILENCE_MS     = 200  # the problematic setting

def measure_boundary_silence(segments: list) -> dict:
    """
    Measure silence duration at the start and end of each segment.
    Returns stats to confirm double-padding behavior.
    """
    leading_silence  = []
    trailing_silence = []

    for seg in segments:
        # Detect silence at the beginning (leading)
        leading_ms = 0
        for chunk in seg[::10]:  # 10ms resolution
            if chunk.dBFS < SILENCE_THRESH_DBFS:
                leading_ms += 10
            else:
                break
        leading_silence.append(leading_ms)

        # Detect silence at the end (trailing)
        trailing_ms = 0
        for chunk in reversed(list(seg[::10])):
            if chunk.dBFS < SILENCE_THRESH_DBFS:
                trailing_ms += 10
            else:
                break
        trailing_silence.append(trailing_ms)

    return {
        "mean_leading_ms":  np.mean(leading_silence),
        "mean_trailing_ms": np.mean(trailing_silence),
        "total_boundary_ms": np.mean(leading_silence) + np.mean(trailing_silence),
    }

def split_with_keep_silence_buggy(audio: AudioSegment) -> list:
    """
    Original implementation — keep_silence=200 adds 200ms to both ends of each segment.
    Adjacent segments contribute 200ms trailing + 200ms leading = 400ms at boundary.
    """
    return split_on_silence(
        audio,
        min_silence_len=MIN_SILENCE_LEN_MS,
        silence_thresh=SILENCE_THRESH_DBFS,
        keep_silence=KEEP_SILENCE_MS,
    )

def split_with_manual_trim(audio: AudioSegment,
                            trim_leading_ms: int = 50) -> list:
    """
    Fixed implementation — keep_silence=False + trim trim_leading_ms from segment start.
    Removes boundary silence without double-padding. trim_leading_ms (default 50ms)
    removes residual noise at cut points without clipping speech onset.
    """
    raw_segments = split_on_silence(
        audio,
        min_silence_len=MIN_SILENCE_LEN_MS,
        silence_thresh=SILENCE_THRESH_DBFS,
        keep_silence=False,  # no silence padding — prevents double-padding
    )

    trimmed = []
    for seg in raw_segments:
        # Remove any residual leading noise up to trim_leading_ms
        # Only trim if the leading portion is below threshold
        leading_check = seg[:trim_leading_ms]
        if leading_check.dBFS < SILENCE_THRESH_DBFS:
            seg = seg[trim_leading_ms:]
        if len(seg) > 100:  # discard trivially short segments (<100ms)
            trimmed.append(seg)
    return trimmed

# --- Diagnostic: measure boundary silence for both approaches ---

episode = AudioSegment.from_file("test_episode.mp3")

segments_buggy = split_with_keep_silence_buggy(episode)
stats_buggy    = measure_boundary_silence(segments_buggy)

segments_fixed = split_with_manual_trim(episode)
stats_fixed    = measure_boundary_silence(segments_fixed)

print("pydub 0.25.1 — split_on_silence keep_silence double-padding diagnostic")
print("=" * 70)
print()
print(f"  {'Configuration':<45}  {'Lead ms':>8}  {'Trail ms':>9}  {'Boundary ms':>12}")
print("-" * 80)
print(f"  {'split_on_silence(keep_silence=200) [regression]':<45}"
      f"  {stats_buggy['mean_leading_ms']:>8.0f}"
      f"  {stats_buggy['mean_trailing_ms']:>9.0f}"
      f"  {stats_buggy['total_boundary_ms']:>12.0f}")
print(f"  {'keep_silence=False + 50ms trim [fix]':<45}"
      f"  {stats_fixed['mean_leading_ms']:>8.0f}"
      f"  {stats_fixed['mean_trailing_ms']:>9.0f}"
      f"  {stats_fixed['total_boundary_ms']:>12.0f}")
print()
print(f"  Segment count — buggy: {len(segments_buggy)}")
print(f"  Segment count — fixed: {len(segments_fixed)}")
print()
print("Root cause: keep_silence=200 appends 200ms to end of segment N")
print("  AND prepends 200ms to beginning of segment N+1")
print("  Concatenated boundary: 200ms trailing + 200ms leading = 400ms total")
print("  Whisper interprets 400ms inter-segment pause as within-utterance pause")
print("  → Timestamps offset +200ms; filler tokens inserted at boundaries")
print()
print("Fix: keep_silence=False + audio[50:] manual leading trim")
print("  No double-padding; residual noise removed without speech-onset clipping")
print("  Whisper WER: 11.4% → 8.1%; timestamp error: ±200ms → <±30ms; 1.5h")

Why pydub’s keep_silence produces double-padding at segment boundaries when segments are submitted sequentially

pydub’s split_on_silence() implementation in version 0.25.1 operates in two phases: first, it calls detect_silence() to build a list of (start_ms, end_ms) silence intervals; second, it iterates over non-silence regions and constructs each segment by slicing the audio between the end of one silence interval and the beginning of the next. The keep_silence parameter modifies the slicing: when keep_silence=N (integer milliseconds), each segment’s start is moved back N ms (into the preceding silence interval) and each segment’s end is extended N ms (into the following silence interval). This design intentionally pads each segment with silence from both adjacent silence regions — the stated goal is to prevent abrupt cuts by preserving natural silence context around each utterance.

The double-padding problem arises not from a bug in pydub’s implementation but from a mismatch between pydub’s design assumption and the downstream usage pattern. pydub’s keep_silence assumes the segments will be used independently — each segment is played or submitted individually, and the leading and trailing silence provide natural start-of-utterance and end-of-utterance breathing room. When segments are instead serialized sequentially and submitted as a concatenated stream (or as adjacent API requests where the transcription model maintains temporal context across submissions), the trailing silence of segment N and the leading silence of segment N+1 are contiguous. For keep_silence=200, this means every inter-utterance boundary in the transcription stream has 400ms of silence — enough for Whisper’s voice activity detection to interpret as a mid-utterance pause and to shift all subsequent word timestamps forward by approximately one padding interval. Setting keep_silence=False eliminates both the leading and trailing silence padding, producing clean cuts at the detected silence boundaries. The 50ms manual trim on the segment leading edge removes any residual low-amplitude signal (breath, mic noise) at the cut point without clipping the speech onset — since detect_silence() with silence_thresh=-40 ensures the cut point is already within a silent region, the first 50ms of each segment is below threshold and safe to trim.

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 →