Learn · Developers

How to remove silence from a video with Python and FFmpeg

Contents

Raw recordings are full of dead air. The speaker breathes, checks a note, waits a beat before the next point. Cut those gaps and the same recording feels sharper, with nothing said removed.

An editor does this by hand, one cut at a time. That’s fine for one video and hopeless for a folder of interviews or a week of contributor clips.

This article does it with two tools. FFmpeg listens to the recording and reports where the silence is. Shotstack’s video editing API then renders a new video with those parts left out. One Python script joins the two, and a second one works through a list of recordings.

TL;DR

  • FFmpeg’s silencedetect filter prints the start and end of every silent part. It reads the file from a URL, so nothing is downloaded by hand.
  • The script turns those times into the parts to keep, then builds one Shotstack edit that plays the kept parts back to back.
  • A 25.87 second talk with five pauses came out at 23.76 seconds. Sound and picture stayed in step at every cut.
  • Three settings control the result: how quiet counts as silence, how long a pause must be, and how much of each pause to leave.
  • A second script runs a list of recordings, video or audio, each with its own settings. Three recordings were done in 65 seconds.

How it works

There are three steps, and the API does the last one.

Find the silence. FFmpeg’s documentation describes the silencedetect filter like this: “Detect silence in an audio stream. This filter logs a message when it detects that the input audio volume is less or equal to a noise tolerance value for a duration greater or equal to the minimum detected noise duration.”

You give it a level and a duration, and it prints times.

Turn silence into the parts to keep. The gaps between the silent parts are the speech. The script leaves a little of each pause in place, so words don’t run into each other.

Render the kept parts in a row. In a Shotstack edit, a clip’s trim says where to start in the source file, and length says how much to play. One clip for each kept part, placed end to end, makes the finished video:

JSON
{
  "asset": {
    "type": "video",
    "src": "https://example.com/talk.mp4",
    "trim": 2.28
  },
  "start": 1.32,
  "length": 8.64
}

This clip plays 8.64 seconds of the recording, from 2.28 seconds in, and puts it 1.32 seconds into the new video.

Remove silence from a video with Python

The script works on a 25.87 second clip of a man talking to the camera, hosted by Shotstack. It finds the pauses, builds the edit, sends it to the API and prints the URL of the result.

You need Python 3 and FFmpeg on your machine. The script uses only Python’s standard library. Put the API key from your Shotstack dashboard in SHOTSTACK_API_KEY first. Renders use credits from your plan.

SOURCE can be any URL that both FFmpeg and Shotstack can reach.

Python
import json
import os
import re
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

API = "https://api.shotstack.io/edit/v1"
SOURCE = "https://shotstack-assets.s3.amazonaws.com/footage/scott-ko.mp4"
NOISE_DB = -30  # sound below this level counts as silence
MIN_SILENCE = 0.4  # seconds; shorter pauses are left alone
KEEP = 0.1  # seconds of each pause to leave beside the speech
STEP = 0.04  # cut points are placed on this grid, in seconds
FRAME_RATES = (12, 15, 24, 25, 30, 48, 50, 60)


def call(url, body=None):
    data = json.dumps(body).encode() if body is not None else None
    headers = {
        "x-api-key": os.environ["SHOTSTACK_API_KEY"],
        "Content-Type": "application/json",
    }
    try:
        request = urllib.request.Request(url, data, headers)
        with urllib.request.urlopen(request) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        sys.exit(f"HTTP {error.code}: {' '.join(error.read().decode().split())[:300]}")


def probe(url):
    """Return the length in seconds and the video stream (None for audio) of a file."""
    encoded = urllib.parse.quote(url, safe="")
    metadata = call(f"{API}/probe/{encoded}")["response"]["metadata"]
    video = None
    for stream in metadata["streams"]:
        if stream["codec_type"] == "video":
            video = stream
    return float(metadata["format"]["duration"]), video


def find_silences(url, duration, noise_db=NOISE_DB, min_silence=MIN_SILENCE):
    """Run FFmpeg's silencedetect filter on the file and return (start, end) pairs."""
    command = ["ffmpeg", "-hide_banner", "-nostats", "-i", url, "-vn"]
    command += ["-af", f"silencedetect=noise={noise_db}dB:d={min_silence}"]
    command += ["-f", "null", "-"]
    log = subprocess.run(command, capture_output=True, text=True, check=False).stderr
    starts = [float(value) for value in re.findall(r"silence_start: (-?[\d.]+)", log)]
    ends = [float(value) for value in re.findall(r"silence_end: ([\d.]+)", log)]
    ends += [duration]  # a silence that runs to the end of the file has no end line
    return list(zip(starts, ends))


def keep_ranges(silences, duration):
    """Return the parts to keep as (start, end) pairs, in whole steps of STEP."""
    ranges, cursor = [], 0.0
    for start, end in silences:
        cut_from = 0.0 if start < STEP else start + KEEP
        cut_to = duration if end > duration - STEP else end - KEEP
        if cut_to - cut_from < STEP:
            continue
        ranges.append((cursor, cut_from))
        cursor = cut_to
    ranges.append((cursor, duration))
    last = int(duration / STEP)  # never ask for footage past the end of the file
    steps = [(round(start / STEP), min(round(end / STEP), last)) for start, end in ranges]
    return [(start, end) for start, end in steps if end > start]


def build_edit(source, ranges, video):
    clips, cursor = [], 0
    for start, end in ranges:
        asset = {"type": "video" if video else "audio", "src": source}
        asset["trim"] = round(start * STEP, 2)
        clip = {"asset": asset, "start": round(cursor * STEP, 2)}
        clip["length"] = round((end - start) * STEP, 2)
        clips.append(clip)
        cursor += end - start
    output = {"format": "mp3"}
    if video:
        top, bottom = video["avg_frame_rate"].split("/")
        fps = min(FRAME_RATES, key=lambda rate: abs(rate - int(top) / int(bottom)))
        size = {"width": video["width"], "height": video["height"]}
        output = {"format": "mp4", "size": size, "fps": fps}
    return {"timeline": {"tracks": [{"clips": clips}]}, "output": output}


def plan(source, **settings):
    """Find the silent parts of a file and return the edit that leaves them out."""
    duration, video = probe(source)
    silences = find_silences(source, duration, **settings)
    ranges = keep_ranges(silences, duration)
    kept = sum(end - start for start, end in ranges) * STEP
    print(f"Source: {duration:.2f} s, {len(silences)} silent parts found")
    print(f"Keeping {len(ranges)} parts, {kept:.2f} s in all ({duration - kept:.2f} s removed)")
    return build_edit(source, ranges, video)


def wait(render_id):
    while True:
        time.sleep(5)
        status = call(f"{API}/render/{render_id}")["response"]
        if status["status"] == "done":
            return status["url"]
        if status["status"] == "failed":
            sys.exit(f"Render failed: {status.get('error')}")


if __name__ == "__main__":
    if not os.environ.get("SHOTSTACK_API_KEY"):
        sys.exit("Set SHOTSTACK_API_KEY first.")
    edit = plan(SOURCE)
    render_id = call(f"{API}/render", edit)["response"]["id"]
    print("Render queued:", render_id)
    url = wait(render_id)
    print(f"Result: {probe(url)[0]:.2f} s")
    print(url)

Save it as remove_silence.py and run it:

Text
Source: 25.87 s, 5 silent parts found
Keeping 4 parts, 23.76 s in all (2.11 s removed)
Render queued: b7e17d1f-5299-4b82-a7c4-2f4707670f28
Result: 23.76 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/b7e17d1f-5299-4b82-a7c4-2f4707670f28.mp4

Here is the original beside the result. The sound is the result’s:

How the script works

  • probe() asks Shotstack’s Probe endpoint for the file’s length, size and frame rate. No download is needed.
  • find_silences() runs FFmpeg with silencedetect and reads the times from its log. -vn tells FFmpeg to skip the picture, so it only decodes the sound.
  • keep_ranges() turns the silent parts into the parts to keep. It leaves KEEP seconds of each pause on both sides, and it cuts a silence at the very start or end of the file completely.
  • Cut points are placed on a grid of 0.04 seconds, one frame at 25 frames a second, so the lengths in the edit are the lengths you get.
  • build_edit() makes one clip for each kept part. The output takes the size of the source and the whole frame rate nearest to it.

Check the result

A shorter file isn’t proof that the cuts are right. I measured three things on the rendered video.

No silence is left. Running silencedetect on the result with the same settings finds nothing.

The sound is the right sound. I compared each kept part of the result with the same part of the source. All four matched, with the result’s sound 6 milliseconds from where the plan put it.

The picture is in step. At the middle of each kept part, the frame in the result is the same frame as in the source. The result has 594 frames, which is exactly 23.76 seconds at 25 frames a second.

The talk only has short pauses, so I also built a harder test: a 20 second clip with three silences of 3, 4.5 and 3 seconds. The script cut it to 10.08 seconds, again frame for frame.

Tune the three settings

The right values depend on the recording. This is what each one did to the 25.87 second talk, with the other two left at the script’s values:

SettingValueSilent parts foundRemoved
NOISE_DB-4021.11 s
NOISE_DB-3052.11 s
NOISE_DB-2083.55 s
MIN_SILENCE0.2122.43 s
MIN_SILENCE0.631.51 s
MIN_SILENCE1.000 s
KEEP052.99 s
KEEP0.251.39 s
  • NOISE_DB is the level below which sound counts as silence. A noisy room needs a higher number, like -20. Go too high and quiet words get cut.
  • MIN_SILENCE is how long a pause must last before it’s cut. At 0.2 seconds the script also cuts the short gaps inside sentences: 12 parts in place of 5. At 1.0 it finds nothing in this talk.
  • KEEP is how much of each pause stays. At 0, nothing of a pause is left and each word is followed at once by the next. The script leaves a tenth of a second on each side, so 0.2 seconds of every pause remains.

Start with the script’s values and change one at a time. Listen to the first few cuts before you run a batch.

Remove silence from a list of recordings

One recording is rarely the whole job. Interviews, podcast episodes and contributor clips arrive in sets, and they don’t all sound the same. A studio voice-over and a clip from a phone need different settings.

So the batch script takes a list where each recording can carry its own settings. It also takes audio files: for an MP3, the result is an MP3.

Python
import time

from remove_silence import API, call, plan, probe, wait

ASSETS = "https://shotstack-assets.s3.amazonaws.com"
RECORDINGS = [
    {"src": f"{ASSETS}/footage/scott-ko.mp4"},
    {"src": f"{ASSETS}/audio/financial-podcast.mp3", "min_silence": 0.5},
    {"src": f"{ASSETS}/footage/avatar-chromakey.mp4", "noise_db": -40},
]

started = time.time()
renders = []
for recording in RECORDINGS:
    source = recording.pop("src")
    print(source.rsplit("/", 1)[-1])
    edit = plan(source, **recording)
    renders.append(call(f"{API}/render", edit)["response"]["id"])

for render_id in renders:
    url = wait(render_id)
    print(f"{probe(url)[0]:.2f} s  {url}")
print(f"All done in {time.time() - started:.0f} s")

Save it next to the first script, as remove_silence_many.py, and run it:

Text
scott-ko.mp4
Source: 25.87 s, 5 silent parts found
Keeping 4 parts, 23.76 s in all (2.11 s removed)
financial-podcast.mp3
Source: 67.38 s, 10 silent parts found
Keeping 10 parts, 63.12 s in all (4.26 s removed)
avatar-chromakey.mp4
Source: 7.20 s, 3 silent parts found
Keeping 2 parts, 4.80 s in all (2.40 s removed)
23.76 s  https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/59ab9e73-4d09-4cf2-ab4c-151aebcae944.mp4
63.14 s  https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/29939c61-4b20-4a2d-ad1d-43eeb4d7e490.mp3
4.80 s  https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/63e93f34-dcb0-4827-af1d-54fe43df63c3.mp4
All done in 65 s

The three results:

The script plans every recording and sends its render request before it waits for any of them. Together the three recordings are 100.45 seconds long, and 8.77 seconds of silence came out. The short avatar clip lost a third of its length, most of it a pause at the end.

Settings change the count a lot. With min_silence at 0.4, the podcast has 17 silent parts. At 0.5 it has 10.

For a larger set, build RECORDINGS from the place the files already live: a folder listing, a database query, a spreadsheet. To stop your code waiting on each render, add a callback URL to the edit and Shotstack calls it when the video is ready. The docs on webhooks show the request it sends.

Can FFmpeg make the cut too?

FFmpeg finds the silence here, so it’s fair to ask whether it can also remove it. It has a filter with the right name. The documentation for silenceremove says: “Remove silence from the beginning, middle or end of the audio.”

The audio, and only the audio. I ran it on the talk, and the sound came out 24.65 seconds long while the picture stayed at 25.84. The two no longer line up.

To cut both, FFmpeg needs the select and aselect filters, with the kept parts written out for each:

Bash
KEEP="between(t,0.56,1.88)+between(t,2.28,10.92)+between(t,11.28,17.88)+between(t,18.12,25.32)"
ffmpeg -i talk.mp4 \
  -vf "select='$KEEP',setpts=N/FRAME_RATE/TB" \
  -af "aselect='$KEEP',asetpts=N/SR/TB" \
  tight.mp4

That works, and it took 6 seconds on my machine. The result needs care, though. The picture came out 23.88 seconds long and the sound 23.78, because the two filters don’t cut at exactly the same points. By the last part, the picture was two frames behind the sound.

For one file on your own computer, that may be close enough. For a batch, you also have to run FFmpeg somewhere, fetch every source file and store every result.

Tighter recordings without an editor

The method is small: let FFmpeg find the quiet parts, keep the rest, and render the kept parts in a row. The settings do the real work, so spend your time there and check the first results by ear.

To run the scripts on your own recordings, sign up for a free Shotstack account and copy the API key from the dashboard.

Frequently asked questions (FAQs)

Will viewers see the cuts?

Yes, on a talking head. Each cut is a jump cut: the speaker’s head moves a little between one frame and the next. The cuts inside this talk remove less than half a second each, so the jump is small.

A long cut makes a bigger jump, and the usual fix is to cover it with other footage on a track above.

Does it work on audio files?

Yes. When the source has no picture, the script builds the edit from audio clips and asks for an MP3. The podcast in the batch above went from 67.38 to 63.14 seconds this way.

What if my recording has background music?

Then there’s little or no silence to find. silencedetect measures the whole soundtrack, and music fills the gaps between words. This method fits recordings where the voice is the only sound, or the loudest by a wide margin.

Can I add captions or music after the cuts?

Yes, and in the same render. The edit is a normal Shotstack timeline, so add more tracks to it before you send it: a soundtrack, a logo, a title. For captions timed to the new cut, see the guide to generating SRT and VTT subtitles.

Keep reading

Start free

  • Unlimited developer sandbox
  • No credit card required