Contents
Merging audio files puts them one after another in a single file: an intro before a podcast episode, the chapters of an audiobook, or a voice line followed by a jingle.
The files rarely match. A voice recording might be mono at 22,050 Hz while the episode is stereo at 48,000 Hz, and a quick join that ignores the difference gives you a file that reports the wrong format and the wrong length.
This guide shows how to merge audio files into one MP3 with Python and Shotstack’s video editing API, then how to do it with FFmpeg without breaking the file.
TL;DR
- Put each file in an
audioclip on one track, one after another, and setoutput.formatto"mp3". - The script below reads each file’s length with the Probe endpoint and starts every file after the one before it, with a 1 second gap.
- It merged a 21.50 second mono voice file and a 67.38 second stereo podcast into one 89.90 second MP3 at 48 kHz stereo, 192 kbps.
- FFmpeg’s fast join with
-c copymislabels mixed files. Itsconcatfilter works when you also set the sample rate and channels.
How merging works with the API
The Edit API renders a timeline that you describe in JSON. For an audio file, the timeline is one track of audio clips, and the output format is mp3. The API reference lists it as “mp3 audio file (audio only)”.
Each clip’s start says where its file begins in the merged MP3. The simplest join sets start to "auto" on every clip. The smart clips guide explains: “For multiple clips, the auto setting stitches clips sequentially according to their order in the track, maintaining their full length.”
{
"timeline": {
"tracks": [
{
"clips": [
{ "asset": { "type": "audio", "src": "https://example.com/intro.mp3" }, "start": "auto", "length": "auto" },
{ "asset": { "type": "audio", "src": "https://example.com/episode.mp3" }, "start": "auto", "length": "auto" }
]
}
]
},
"output": { "format": "mp3" }
}The script below sets each start itself instead. It needs the lengths anyway to print them, and numbers let it put a pause between files.
Merge audio files with Python
The script merges two files hosted by Shotstack: a 21 second voice-over and a 67 second podcast clip. It prints each file’s length and format, where it starts in the merged file, and what the result looks like.
The script uses only the Python standard library. Set SHOTSTACK_API_KEY to the API key from your Shotstack dashboard, then run it with Python 3. Each render uses credits from your plan, as listed on the pricing page.
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
API = "https://api.shotstack.io/edit/v1"
ASSETS = "https://shotstack-assets.s3.amazonaws.com"
FILES = [
f"{ASSETS}/audio/polly-voiceover.mp3",
f"{ASSETS}/audio/financial-podcast.mp3",
]
GAP = 1.0 # seconds of silence between files; 0 joins them end to end
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 duration, sample rate and channel count of an audio file at a URL."""
encoded = urllib.parse.quote(url, safe="")
metadata = call(f"{API}/probe/{encoded}")["response"]["metadata"]
audio = next(s for s in metadata["streams"] if s["codec_type"] == "audio")
duration = float(metadata["format"]["duration"])
return duration, audio["sample_rate"], audio["channels"]
def build_edit(clips):
track = [
{"asset": {"type": "audio", "src": url}, "start": start, "length": length}
for url, start, length in clips
]
return {"timeline": {"tracks": [{"clips": track}]}, "output": {"format": "mp3"}}
if __name__ == "__main__":
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
clips, start = [], 0.0
for url in FILES:
length, rate, channels = probe(url)
clips.append((url, round(start, 3), round(length, 3)))
name = url.rsplit("/", 1)[-1]
print(f"{name}: {length:.2f} s, {rate} Hz, {channels} ch, at {start:.2f} s")
start += length + GAP
render_id = call(f"{API}/render", build_edit(clips))["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')}")
length, rate, channels = probe(status["url"])
print(f"Merged MP3: {length:.2f} s, {rate} Hz, {channels} ch")
print(status["url"])Run python merge_audio.py. It prints a line for each file, the render ID, the merged MP3’s length and format, and its URL:
polly-voiceover.mp3: 21.50 s, 22050 Hz, 1 ch, at 0.00 s
financial-podcast.mp3: 67.38 s, 48000 Hz, 2 ch, at 22.50 s
Render queued: 4389a0da-15a6-4135-b0e0-a199a414c7f8
Merged MP3: 89.90 s, 48000 Hz, 2 ch
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/35tqpmb0ya/4389a0da-15a6-4135-b0e0-a199a414c7f8.mp3This is the merged MP3 from that run:
How the script works
probe()sends each file’s URL to the Probe endpoint and returns its length, sample rate and number of channels.- The main block walks through
FILESin order. Each file starts where the one before it ends, plusGAPseconds. build_edit()makes oneaudioclip per file on a single track and asks for anmp3.- After the render, the script probes the merged file and prints its length and format.
What the merged file contains
The two files don’t share a format. The merged MP3 has one format for all of it:
| Voice-over | Podcast | Merged MP3 | |
|---|---|---|---|
| Length | 21.50 s | 67.38 s | 89.90 s |
| Sample rate | 22,050 Hz | 48,000 Hz | 48,000 Hz |
| Channels | 1 (mono) | 2 (stereo) | 2 (stereo) |
| Bitrate | 48 kbps | 129 kbps | 192 kbps |
The voice-over plays from 0 seconds and the podcast from 22.50 seconds. The second in between is silent. Set GAP = 0 to join the files with no pause.
Merge audio files with FFmpeg
FFmpeg has two ways to join files on your own machine. The fast one is the concat demuxer, which reads a list of files and copies their audio without encoding it again:
printf "file 'intro.mp3'\nfile 'episode.mp3'\n" > list.txt
ffmpeg -f concat -safe 0 -i list.txt -c copy merged.mp3Copying only works when every file has the same format. With the two files above, the result is labeled 22,050 Hz mono, from the first file, and ffprobe reports 94.82 seconds for 88.87 seconds of audio.
The concat filter decodes the files and encodes the result again, so it can join mixed files:
ffmpeg -i intro.mp3 -i episode.mp3 -filter_complex "[0:a][1:a]concat=n=2:v=0:a=1" -ar 48000 -ac 2 -b:a 192k merged.mp3Keep -ar 48000 -ac 2 at the end. Without them, the merged file takes the first file’s format: 22,050 Hz mono at 32 kbps, which turns the stereo podcast into mono. With them, the result is 48 kHz stereo and 88.87 seconds long.
Merge your audio with Shotstack
You now have a script that merges any number of audio files into one MP3, in order, with a pause between them if you want one. Put your own URLs in FILES and run it again.
Create a free Shotstack account to get your API key and merge your first files.
Frequently asked questions (FAQs)
Can I fade between the files?
Yes. An audio asset takes an effect of fadeIn, fadeOut or fadeInFadeOut. Add "effect": "fadeInFadeOut" to each clip’s asset to fade every file in and out.
Can I turn the merged audio into a video?
Yes. Change output.format to "mp4" and add an image clip with "length": "end" on a track above the audio. Our guide on how to convert MP3 to MP4 with Python shows the whole edit.
Can I merge files that are on my computer?
Yes. Each entry in FILES has to be a URL that Shotstack can fetch, so upload the files first. The Ingest API gives you an upload link and returns each file’s URL when it’s ready.