Contents
Trimming audio means keeping one part of a recording and dropping the rest: a 30 second preview of a song, one answer from an hour of podcast, a voice note without the dead air at the start.
An audio editor does that well for one file. When the files come from users, or there are hundreds of them, the cut has to happen in code.
Here’s how to trim audio with Python and Shotstack’s video editing API, which edits audio files too. One script cuts a part out of an MP3, fades it out and saves it as a new MP3. A second cuts many parts out of one recording.
The FFmpeg section at the end compares two ways to make the same cut, measured on the same song.
TL;DR
- An audio clip’s
trimis where the part to keep starts, and the clip’slengthis how much of it to keep."format": "mp3"makes the output an audio file. - The script below cut seconds 20 to 50 out of a 222.56 second song in one render.
- The new MP3 starts within a millisecond of the 20 second mark, and its fade covers the last 2 seconds.
- To cut many parts out of one recording, a second script sends one render for each. Three clips from a 67 second file took about half a second each to render.
- FFmpeg’s
-c copycut skips the re-encode but lands on an MP3 frame. It started 4 milliseconds early.
How trimming audio works with the API
A Shotstack edit is a timeline, and the timeline doesn’t need a picture: with one audio clip on it and an audio output format, the result is an audio file.
This edit keeps 30 seconds of a song, starting 20 seconds in:
{
"timeline": {
"tracks": [
{
"clips": [
{
"asset": {
"type": "audio",
"src": "https://example.com/song.mp3",
"trim": 20,
"effect": "fadeOut"
},
"start": 0,
"length": 30
}
]
}
]
},
"output": { "format": "mp3" }
}Three settings make the cut:
trimis where the part to keep begins, in seconds from the start of the file.lengthis how many seconds to keep.formatismp3, which the API reference lists as “mp3 audio file (audio only)”.
Trim an audio file with Python
The script cuts a 30 second preview out of a 222.56 second song, hosted by Shotstack. It reads the song’s length, sends the edit, waits for the render and prints the URL of the new MP3.
The script needs Python 3 and no packages. It reads your API key from SHOTSTACK_API_KEY; the key is in your Shotstack dashboard. Each render uses credits from your plan, at the rates on the pricing page.
SOURCE is a URL. To trim a file from your own disk, upload it with the Ingest API and use the URL it returns.
import json
import os
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/music/unminus/lit.mp3"
START = 20 # where the part to keep begins, in seconds
LENGTH = 30 # how many seconds to keep
FADE = "fadeOut" # "fadeIn", "fadeOut", "fadeInFadeOut" or None
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 of the audio file at a URL."""
encoded = urllib.parse.quote(url, safe="")
metadata = call(f"{API}/probe/{encoded}")["response"]["metadata"]
return float(metadata["format"]["duration"])
def build_edit():
audio = {"type": "audio", "src": SOURCE, "trim": START}
if FADE:
audio["effect"] = FADE
clip = {"asset": audio, "start": 0, "length": LENGTH}
return {
"timeline": {"tracks": [{"clips": [clip]}]},
"output": {"format": "mp3"},
}
if __name__ == "__main__":
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
duration = probe(SOURCE)
if START + LENGTH > duration:
sys.exit(f"The file is {duration:.2f} s long. Lower START or LENGTH.")
print(f"Source: {duration:.2f} s")
print(f"Keeping {START:.2f} s to {START + LENGTH:.2f} s")
render_id = call(f"{API}/render", build_edit())["response"]["id"]
print("Render queued:", render_id)
while True:
time.sleep(5)
status = call(f"{API}/render/{render_id}")["response"]
if status["status"] == "done":
break
if status["status"] == "failed":
sys.exit(f"Render failed: {status.get('error')}")
print(f"MP3: {probe(status['url']):.2f} s")
print(status["url"])Run python trim_audio.py. It prints the length of the source, the part it keeps, the render ID, the length of the new file and its URL:
Source: 222.56 s
Keeping 20.00 s to 50.00 s
Render queued: 20be79de-53d4-4853-ae30-685dc891d4ff
MP3: 30.02 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/20be79de-53d4-4853-ae30-685dc891d4ff.mp3This is the trimmed file:
How the script works
probe()sends a file’s URL to the Probe endpoint and returns its length.- The main block stops with a clear message when
STARTplusLENGTHruns past the end of the file. build_edit()puts the audio on one clip, setstrimtoSTARTand the clip’slengthtoLENGTH, and adds the fade whenFADEhas a value.- Then it sends the edit, waits for the render and prints the new file’s length and URL.
What the new MP3 contains
The new file starts within a millisecond of the 20 second mark of the source, and it holds 30.00 seconds of sound.
| Source | Trimmed file | |
|---|---|---|
| Length | 222.56 s | 30.00 s |
| Sample rate | 44.1 kHz | 48 kHz |
| Channels | Stereo | Stereo |
| Bitrate | 320 kbps | 192 kbps |
| File size | 8.9 MB | 0.7 MB |
The script prints 30.02 seconds for the file. MP3 stores sound in frames, 24 milliseconds each at 48 kHz, and this file has 1,251 of them: one more than 30 seconds needs.
The source is 44.1 kHz and the trimmed file is 48 kHz: the render converts it. Our guide to audio sample rate for video explains the two rates.
Add a fade
A cut in the middle of a song stops dead, so the script sets FADE to "fadeOut". The sound plays at full volume until 2 seconds before the end, then drops to silence.
FADE takes any of the audio effects in the API reference: "fadeIn", "fadeOut" or "fadeInFadeOut". Set it to None and the file starts and ends on the cut.
Trim audio at scale
The usual batch for audio is one long recording and many cuts: the chapters of a podcast, the songs of a live set, the answers in an interview. Each cut is its own render, and the script sends them all before it waits for any.
The second script, trim_many.py, imports the first one, saved as trim_audio.py. It points it at a 67 second podcast ad, reads the file’s length once, and cuts three parts out of it. A part that runs past the end is skipped:
import os
import sys
import time
import trim_audio
ASSETS = "https://shotstack-assets.s3.amazonaws.com"
trim_audio.SOURCE = f"{ASSETS}/audio/financial-podcast.mp3"
# The parts to cut out of the recording: where each begins and how long it is.
CUTS = [(0, 15), (20, 20), (45, 20)]
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
began = time.time()
duration = trim_audio.probe(trim_audio.SOURCE)
print(f"Source: {duration:.2f} s")
renders = {}
for start, length in CUTS:
if start + length > duration:
print(f"Skipped {start} s to {start + length} s: past the end of the file")
continue
trim_audio.START, trim_audio.LENGTH = start, length
edit = trim_audio.build_edit()
response = trim_audio.call(f"{trim_audio.API}/render", edit)
renders[response["response"]["id"]] = (start, start + length)
print(f"Queued {len(renders)} cuts")
while renders:
time.sleep(5)
for render_id, (start, end) in list(renders.items()):
url = f"{trim_audio.API}/render/{render_id}"
status = trim_audio.call(url)["response"]
if status["status"] in ("done", "failed"):
del renders[render_id]
result = status.get("url") or status.get("error")
print(f"{start:2} s to {end:2} s {status['status']} {result}")
print(f"All done in {time.time() - began:.0f} s")Run python trim_many.py. It prints the recording’s length, then each part with its time range and the URL of its MP3:
Source: 67.38 s
Queued 3 cuts
0 s to 15 s done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/686f3118-5ca5-44da-a0a0-d31444a453f9.mp3
20 s to 40 s done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/4c83e989-6a5c-4dca-a34b-fd7c6400905b.mp3
45 s to 65 s done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/ce2eeb83-8bfd-4122-aa37-0ce3f3361580.mp3
All done in 16 sThree MP3 files, 15, 20 and 20 seconds long, came out of one 67.38 second recording. Each render took about half a second. The script had all three 16 seconds after it started, and most of that was waiting between checks.
Every part gets the fade that FADE sets. Here are the three parts, in order:
For a show that comes out every week, the list of cuts is the only thing that changes. Our guide on how to automate video creation on a schedule puts a script like this one on cron and skips the items it has already done.
Trim audio with FFmpeg
FFmpeg can make the same cut on your own machine. The fastest way copies the audio without encoding it again:
ffmpeg -ss 20 -t 30 -i input.mp3 -c copy output.mp3-ss is where to start and -t is how long to keep. Both go before -i, where the FFmpeg documentation says -t will “limit the duration of data read from the input file.”
A copy can only cut between MP3 frames. The same page says of -ss that “in most formats it is not possible to seek exactly, so ffmpeg will seek to the closest seek point before position.”
On this song the copy started 4 milliseconds before the 20 second mark and came out 30.04 seconds long. An MP3 frame at 44.1 kHz is 26 milliseconds long, so a copy can start up to that much early.
To cut on the exact sample, or to add a fade, let FFmpeg encode the audio again:
ffmpeg -ss 20 -t 30 -i input.mp3 -af "afade=t=out:st=28:d=2" -b:a 192k output.mp3-c copy | Encode again | |
|---|---|---|
| Start of the cut | 4 ms early | On the mark |
| Length | 30.04 s | 30.00 s |
| Quality | Same as the source, 320 kbps | Set with -b:a |
| Fade | Not possible | afade filter |
Our guide on how to trim a video with FFmpeg covers -ss and -t in more depth.
Cut audio at scale with Shotstack
One audio clip with a trim and a length is the whole cut, and "format": "mp3" turns the render into an audio file. On whole seconds the cut lands within a millisecond, and a list of cuts takes one render each. Put your own file’s URL in SOURCE and your own parts in CUTS to try it.
Create a free Shotstack account, grab your API key and trim your first file.
Frequently asked questions (FAQs)
Can I cut out the middle of a file and keep both ends?
Yes. Put two audio clips on the same track, one after the other. The first keeps the opening with a trim of 0. The second starts where the first one ends and has a trim at the point where the sound picks up again. Our guide on how to merge audio files joins different files the same way.
Can I get the sound of a video as an MP3?
Yes. Our guide on how to convert MP4 to MP3 with Python takes the audio out of a video file.
Can START and LENGTH be fractions of a second?
Yes, in steps of 0.04 seconds. A START of 20.5 with a LENGTH of 7.25 gave a file that starts at 20.52 seconds and is 7.24 seconds long. Use multiples of 0.04, such as 20.48 or 20.52, and the cut lands where you set it.