Backing tracks and stems often come with a few seconds of silence at the start and a long fade or dead air at the end. For a karaoke set or a practice playlist that wastes time and makes the count-in unpredictable. Here is a small Python script that trims leading and trailing silence from a folder of audio files with pydub, while keeping a short, consistent lead-in.

Install

pip install pydub 

pydub uses ffmpeg for anything other than WAV, so install ffmpeg as well and make sure it is on your PATH.

The script

import sys from pathlib import Path from pydub import AudioSegment from pydub.silence import detect_leading_silence KEEP_HEAD_MS = 300 # keep a short lead-in so the first beat is not clipped KEEP_TAIL_MS = 800 # keep a little room after the last note THRESH_OFFSET_DB = 30 # silence = quieter than (track loudness - 30 dB) def trim(seg: AudioSegment) -> AudioSegment: thresh = seg.dBFS - THRESH_OFFSET_DB head = detect_leading_silence(seg, silence_threshold=thresh) tail = detect_leading_silence(seg.reverse(), silence_threshold=thresh) start = max(0, head - KEEP_HEAD_MS) end = min(len(seg), len(seg) - tail + KEEP_TAIL_MS) return seg[start:end] def main(folder): folder = Path(folder) out = folder / "trimmed" out.mkdir(exist_ok=True) for f in sorted(folder.iterdir()): if f.suffix.lower() not in (".wav", ".flac", ".mp3", ".m4a"): continue seg = AudioSegment.from_file(f) t = trim(seg) t.export(out / (f.stem + ".wav"), format="wav") print(f"{f.name}: {len(seg)/1000:.1f}s -> {len(t)/1000:.1f}s") if __name__ == "__main__": main(sys.argv[1] if len(sys.argv) > 1 else ".") 

Why a relative threshold

A fixed threshold such as -50 dBFS works for loud, mastered tracks but cuts into quiet acoustic intros. Setting the threshold relative to the track's average loudness (seg.dBFS - 30) adapts to each file: a loud pop instrumental and a soft piano backing both get trimmed at a sensible point.

Things to watch

  • Fade-outs. A long fade will be kept until it drops below the threshold. If you want the fade shorter, add t = t.fade_out(2000) after trimming.
  • Count-ins. If a track starts with a drummer's stick clicks, they are loud enough to be kept, which is usually what singers want.
  • Lossy input. The script always writes WAV, so you do not stack another round of MP3 encoding on top of the original.

Where this fits

I run this after separating the vocal from a song, because separated instrumentals often keep the original's silent padding. The separation step itself I do in the browser with Video Vocal Remover, then trim and level the whole folder before a session.

pydub silence helpers: https://github.com/jiaaro/pydub/blob/master/pydub/silence.py