Contents
A long video often has to become several short ones: a webinar cut into chapters, a recording cut into clips of a fixed length, or one file cut into pieces that fit an upload limit.
This guide shows how to split a video into parts with Python and Shotstack’s video editing API. The script reads the length of a video at a URL, works out where each part starts, and renders every part as its own MP4.
The cuts are exact: every frame of the source ends up in one part, and only one.
TL;DR
- A part is one render: a video clip with
trimset to where the part starts andlengthset to how long it runs. - The Probe endpoint gives you the length of the source, so the script can work out every cut point.
- The script below split a 29.44 second video into three files of 10.00, 10.00 and 9.44 seconds.
- The three parts had 250, 250 and 236 frames: 736 in total, the same number as the source.
- No frame is lost or repeated where one part ends and the next begins.
How splitting works with the API
The Edit API renders what you describe in JSON. To get one part of a longer video, you describe a single clip:
srcis the URL of the full video.trimis the number of seconds to skip from the start of the source.lengthis how long the clip plays.
The second 10 second part of a video looks like this:
{
"asset": { "type": "video", "src": "https://example.com/video.mp4", "trim": 10 },
"start": 0,
"length": 10
}To split a whole video, you send one of these for each part. Every request is its own render.
Split a video into parts with Python
The script below splits a 29.44 second skateboarding clip, hosted by Shotstack, into parts of 10 seconds. The last part takes whatever is left.
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"
SOURCE = "https://shotstack-assets.s3.amazonaws.com/footage/skateboarder.mp4"
PART_SECONDS = 10
FRAME_RATES = (12, 15, 23.976, 24, 25, 29.97, 30, 48, 50, 59.94, 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 duration in seconds and the frame rate of a video at a URL."""
encoded = urllib.parse.quote(url, safe="")
metadata = call(f"{API}/probe/{encoded}")["response"]["metadata"]
video = next(s for s in metadata["streams"] if s["codec_type"] == "video")
top, bottom = video["avg_frame_rate"].split("/")
return float(video["duration"]), int(top) / int(bottom)
def plan(duration, part_seconds):
"""Return (start, length) for each part. The last part takes what is left."""
parts, start = [], 0.0
while start < duration - 0.01:
length = min(part_seconds, duration - start)
parts.append((round(start, 3), round(length, 3)))
start += part_seconds
return parts
def build_edit(start, length, fps):
clip = {
"asset": {"type": "video", "src": SOURCE, "trim": start},
"start": 0,
"length": length,
}
return {
"timeline": {"tracks": [{"clips": [clip]}]},
"output": {"format": "mp4", "resolution": "hd", "fps": fps},
}
if __name__ == "__main__":
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
duration, source_fps = probe(SOURCE)
fps = min(FRAME_RATES, key=lambda rate: abs(rate - source_fps))
parts = plan(duration, PART_SECONDS)
print(f"Source: {duration:.2f} s at {source_fps:g} fps, {len(parts)} parts")
renders = [
call(f"{API}/render", build_edit(start, length, fps))["response"]["id"]
for start, length in parts
]
for number, render_id in enumerate(renders, 1):
while True:
status = call(f"{API}/render/{render_id}")["response"]
if status["status"] == "done":
break
if status["status"] == "failed":
sys.exit(f"Part {number} failed: {status.get('error')}")
time.sleep(3)
filename = f"part-{number:02}.mp4"
urllib.request.urlretrieve(status["url"], filename)
start, length = parts[number - 1]
seconds, _ = probe(status["url"])
print(
f"{filename} from {start:6.2f} s asked {length:5.2f} s got {seconds:5.2f} s"
)Run python split_video.py. It saves the parts in the current folder and prints one line for each:
Source: 29.44 s at 25 fps, 3 parts
part-01.mp4 from 0.00 s asked 10.00 s got 10.00 s
part-02.mp4 from 10.00 s asked 10.00 s got 10.00 s
part-03.mp4 from 20.00 s asked 9.44 s got 9.44 sThis video plays the full video on top and the three parts below it. Each part lights up while its section of the full video plays:
How the script works
probe()sends the video’s URL to the Probe endpoint and returns its duration and frame rate.plan()walks through the video in steps ofPART_SECONDS. It returns a start time and a length for each part, and the last part gets the time that remains.build_edit()makes the edit for one part, withtrimandlengthfrom the plan.- The script posts every render first and collects the IDs. Then it waits for each one, downloads it, and names it
part-01.mp4,part-02.mp4and so on. - After each download, it probes the finished file and prints the length it asked for next to the length it got.
The script also sets the output frame rate. It picks the value closest to the source’s own rate from the list the API accepts, so a 25 fps source is rendered at 25 fps. Our guide on how to change the frame rate of a video shows what happens to the frames when the two rates differ.
Do the parts line up?
A split is only useful if nothing goes missing at the cuts. Here is a 12 second clip at 30 fps, with a number on each of its 360 frames, split into four parts of 3 seconds by the same plan() and build_edit() functions. The table reads the numbers back from every frame of every part.
| Part | Frames in the file | First frame | Last frame |
|---|---|---|---|
| 1 | 90 | 0 | 89 |
| 2 | 90 | 90 | 179 |
| 3 | 90 | 180 | 269 |
| 4 | 90 | 270 | 359 |
Each part starts on the frame after the previous part’s last frame. All 360 frames appear once.
Split a video with FFmpeg
FFmpeg can split a file on your own machine with its segment muxer. The fast version copies the streams without encoding them again:
ffmpeg -i input.mp4 -c copy -f segment -segment_time 10 -reset_timestamps 1 part-%02d.mp4A copied stream can only be cut at a keyframe, so the parts are not always the length you asked for. The FFmpeg formats documentation says: “Note that splitting may not be accurate, unless you force the reference stream key-frames at the given time.”
To get exact lengths, encode the video again and force a keyframe every 10 seconds:
ffmpeg -i input.mp4 -c:v libx264 -crf 18 -force_key_frames "expr:gte(t,n_forced*10)" -c:a aac -f segment -segment_time 10 -reset_timestamps 1 part-%02d.mp4On the skateboarding clip, which has a keyframe every 3.04 seconds, the methods give these parts:
| Method | Part 1 | Part 2 | Part 3 |
|---|---|---|---|
| FFmpeg, stream copy | 12.16 s | 9.12 s | 8.16 s |
| FFmpeg, encode with forced keyframes | 10.00 s | 10.00 s | 9.44 s |
| Shotstack script | 10.00 s | 10.00 s | 9.44 s |
Our guide on how to trim a video with FFmpeg covers cutting a single section.
Tips for choosing the parts
- Split into a number of parts. To get four equal parts, set
PART_SECONDSto the duration divided by four. For the 29.44 second clip, that is 7.36 seconds each. - Watch the last part. A 61.2 second video split at 60 seconds gives a second part of 1.2 seconds. Pick a part length that divides the video more evenly, or drop the last item from
partswhen it is too short to use. - Cut at your own times.
plan()returns a list of start times and lengths. Replace it with your own list, such as chapter times, and the rest of the script stays the same. - Keep the source’s shape. The script renders at
hd, which is 1280 x 720. For a vertical video, add"aspectRatio": "9:16"to the output.
Split your videos with Shotstack
You now have a script that splits a video at a URL into parts of any length, and a check that shows the parts meet frame for frame. Put your own video URL in SOURCE, set PART_SECONDS, and run it again.
Create a free Shotstack account to get your API key and split your first video.
Frequently asked questions (FAQs)
Can I cut out one section and keep only that?
Yes. Send a single render with trim set to where the section starts and length set to how long it is. Our guide on how to trim videos using Python walks through it.
Can I pick the best moments instead of equal parts?
Yes, when you know where they are. Give the script your own list of start times and lengths. To find the moments automatically from what is said in the video, see our video clipping pipeline.
Do I have to wait for each part before I start the next?
No. The script posts all of the renders before it waits for any of them. For a long video with many parts, you can also give each render a callback URL and let the API tell you when it is done. The webhooks guide explains how.
How do I see where the keyframes are in my file?
Run ffprobe -v error -select_streams v:0 -skip_frame nokey -show_entries frame=pts_time -of csv=p=0 input.mp4. It prints the time of every keyframe. For the skateboarding clip the list starts 0.00, 3.04, 6.08 and 9.12, which is why the stream copy made a first part of 12.16 seconds: the first keyframe at or after 10 seconds is at 12.16.