Contents
A loop plays the same clip again and again. Ten seconds of rain becomes a minute of background, a product spin keeps turning under a voiceover, and a short animation fills a whole song.
Here’s how to loop a video with Python and Shotstack’s video editing API. The first script repeats a clip a set number of times, or until a soundtrack ends, and a second one makes several lengths from the same clip. FFmpeg comes last: it can loop a file without encoding it again.
TL;DR
- To loop a video, put the same clip on one track several times. Each copy starts where the one before it ends.
- The script below played a 10.55 second clip 3 times in one render. The result is 31.67 seconds long.
- Set
AUDIOand the video loops until the soundtrack ends, with the last copy cut to fit. - In a test with numbered frames, the last frame of one copy is followed by the first frame of the next at each seam. No frame is repeated or dropped.
- A second script makes several lengths from one clip. Its 15, 30 and 60 second versions each took 5 to 6 seconds to render.
How looping works with the API
A Shotstack edit is a timeline of tracks. A track holds clips in a row, each with its own start time, and nothing stops two clips from using the same video. A loop is one clip, placed again and again.
This track plays a 10 second video twice:
{
"clips": [
{
"asset": { "type": "video", "src": "https://example.com/clip.mp4" },
"start": 0,
"length": 10
},
{
"asset": { "type": "video", "src": "https://example.com/clip.mp4" },
"start": 10,
"length": 10
}
]
}Two numbers set each copy: start is when it begins on the timeline, and length is how long it plays. For a clean loop, every start is the one before it plus the video’s exact length.
Loop a video with Python
The script loops a 10.55 second clip of rain on a roof, hosted by Shotstack. It reads the clip’s length and frame rate, places three copies back to back and renders them as one video.
The script is plain Python 3, with no packages to install. It expects your API key in SHOTSTACK_API_KEY; you’ll find the key in the Shotstack dashboard. Rendering uses credits, and the pricing page has the rates.
SOURCE must be a URL. For a clip on your own disk, upload it with the Ingest API and use the URL it gives back.
import json
import math
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.ap-southeast-2.amazonaws.com"
SOURCE = f"{ASSETS}/footage/rain-on-roof.mp4"
LOOPS = 3 # how many times the video plays
AUDIO = None # URL of a soundtrack; when set, the video loops until it ends
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 frame rate (None for audio) of a file."""
encoded = urllib.parse.quote(url, safe="")
metadata = call(f"{API}/probe/{encoded}")["response"]["metadata"]
fps = None
for stream in metadata["streams"]:
if stream["codec_type"] == "video":
top, bottom = stream["avg_frame_rate"].split("/")
fps = int(top) / int(bottom)
return float(metadata["format"]["duration"]), fps
def build_edit(duration, total, fps):
clips = []
for number in range(math.ceil(round(total / duration, 6))):
start = round(number * duration, 3)
length = round(min(duration, total - start), 3)
video = {"type": "video", "src": SOURCE}
if AUDIO:
video["volume"] = 0
clips.append({"asset": video, "start": start, "length": length})
tracks = [{"clips": clips}]
if AUDIO:
audio = {"type": "audio", "src": AUDIO}
tracks.append({"clips": [{"asset": audio, "start": 0, "length": total}]})
return {
"timeline": {"tracks": tracks},
"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)
total = probe(AUDIO)[0] if AUDIO else LOOPS * duration
fps = min(FRAME_RATES, key=lambda rate: abs(rate - source_fps))
print(f"Source: {duration:.2f} s at {source_fps:.6g} fps")
print(f"Looping {total / duration:.2f} times, {total:.2f} s in all")
edit = build_edit(duration, total, fps)
render_id = call(f"{API}/render", 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"Video: {probe(status['url'])[0]:.2f} s")
print(status["url"])Run python loop_video.py. It prints the source’s length and frame rate, the number of loops, the render ID, the length of the result and the URL of the video:
Source: 10.55 s at 23.976 fps
Looping 3.00 times, 31.66 s in all
Render queued: befb4f25-b673-4ce5-a6dd-cbc4bdd15c3a
Video: 31.67 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/befb4f25-b673-4ce5-a6dd-cbc4bdd15c3a.mp4Here’s the result, with a label that counts the loops:
How the script works
probe()sends a file’s URL to the Probe endpoint and returns its length, plus the frame rate when it’s a video.- The main block works out the total length:
LOOPStimes the video’s length, or the length of the soundtrack whenAUDIOis set. build_edit()adds copies of the clip until the total is covered. Each copy starts at a multiple of the video’s length.- The last copy is cut short when the total isn’t a whole number of loops.
- The output uses the whole frame rate closest to the source’s own, so this 23.976 fps clip is rendered at 24 fps. That’s why the result is 31.67 seconds and not 31.66: at 24 fps the video rounds up to 760 whole frames.
Loop a video until the soundtrack ends
A set number of loops works when you know the length you want. Often the sound decides instead: a voiceover or a song has a fixed length, and the picture has to last that long.
Set AUDIO to the URL of a soundtrack. The script then reads its length, mutes the video and loops the picture until the sound ends. With a 21.498 second voiceover over the 10.552 second rain clip, it builds these three copies:
| Copy | Starts at | Plays for |
|---|---|---|
| 1 | 0 s | 10.552 s |
| 2 | 10.552 s | 10.552 s |
| 3 | 21.104 s | 0.394 s |
The result is 21.50 seconds long: two full loops and the first 0.39 seconds of a third.
What happens at the seam
A loop is only as smooth as its seam, so here’s a frame-level look. A 12 second, 30 fps video with its frames numbered from 0 to 359, looped 2.5 times, comes out as 900 frames:
| Output frames | Source frames shown |
|---|---|
| 0 to 359 | 0 to 359 |
| 360 to 719 | 0 to 359 |
| 720 to 899 | 0 to 179 |
Frame 359 is followed by frame 0 at both seams, and every other frame follows the one before it. Nothing is repeated, dropped or blended.
That test clip is a whole number of frames long. The rain clip isn’t at 24 fps (253.25 frames), so in its 60 second version one seam, the third, holds its last frame for one extra frame.
So the render adds no jump of its own. What you see at the seam is the difference between the clip’s last frame and its first. Footage like rain, waves or a turning product hides it well.
Make a GIF that loops
A GIF carries its own loop setting, so the clip goes on the timeline once. Set the output format to gif and repeat to true:
{ "format": "gif", "repeat": true }The API reference describes repeat in one line: “Set to true to loop, false to play only once.” With true, the GIF file is marked to loop forever. With false, it has no loop mark and plays once. Our guide on how to convert MP4 to GIF with Python covers the rest of the GIF output.
Loop videos at scale
One good loop usually has to fill several slots: a 15 second story, a 30 second ad, a minute of background behind a talk. The clip is the same each time. Only the length changes.
loop_many.py imports the first script, saved as loop_video.py, and makes one version for each length in a list. build_edit() cuts the last copy short, so every version ends on the second:
import os
import sys
import time
import loop_video
LENGTHS = [15, 30, 60] # the versions to make from the one clip, in seconds
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
began = time.time()
duration, source_fps = loop_video.probe(loop_video.SOURCE)
fps = min(loop_video.FRAME_RATES, key=lambda rate: abs(rate - source_fps))
renders = {}
for seconds in LENGTHS:
edit = loop_video.build_edit(duration, seconds, fps)
response = loop_video.call(f"{loop_video.API}/render", edit)
renders[response["response"]["id"]] = seconds
print(f"Queued {len(renders)} versions of a {duration:.2f} s clip")
while renders:
time.sleep(5)
for render_id, seconds in list(renders.items()):
url = f"{loop_video.API}/render/{render_id}"
status = loop_video.call(url)["response"]
if status["status"] in ("done", "failed"):
del renders[render_id]
result = status.get("url") or status.get("error")
print(f"{seconds:2} s {status['status']} {result}")
print(f"All done in {time.time() - began:.0f} s")Run python loop_many.py. It prints each version’s length and URL as it finishes:
Queued 3 versions of a 10.55 s clip
15 s done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/d046f03a-77ce-418e-a640-a1ce5c6c9201.mp4
30 s done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/02bd39ba-8669-47ef-a097-b56e5853c78f.mp4
60 s done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/d66d03ed-569e-4a9c-a9c4-0dad5e920ed1.mp4
All done in 17 sThe 10.55 second rain clip became 15, 30 and 60 second videos, 105 seconds in all. Each took 5 to 6 seconds to render, and the script had all three 17 seconds after it started. The 60 second version plays the clip 5 times, then the first 7.24 seconds of a sixth.
This video plays the three versions together. Each one dims when its length is up:
To loop many different clips, wrap the same code in a loop over their URLs. For a large batch, our guide on how to generate videos in bulk covers a test run, resuming and retries.
Loop a video with FFmpeg
FFmpeg can loop a file on your own machine with -stream_loop, placed before -i:
ffmpeg -stream_loop 2 -i input.mp4 -c copy output.mp4The FFmpeg documentation defines the option like this: “Set number of times input stream shall be looped. Loop 0 means no loop, loop -1 means infinite loop.”
The number counts the repeats after the first play, so 2 plays the video three times. With -c copy nothing is encoded again. On the rain clip the command gave 759 frames, 3 times the source’s 253, and 31.66 seconds, in a file three times the size of the source.
To loop until a soundtrack ends, loop the video without end and let -shortest stop the output when the audio does:
ffmpeg -stream_loop -1 -i input.mp4 -i music.mp3 -map 0:v -map 1:a -c:v copy -shortest output.mp4With the same rain clip and voiceover, that gives 21.48 seconds of video. A copy can’t cut at an exact time, so the video stops on its last whole packet, just short of the 21.50 second voiceover.
Loop your videos with Shotstack
A loop is one clip placed again and again, each copy starting where the last one ends. Whole copies join frame to frame, a soundtrack or a target length cuts the last copy to fit, and one clip becomes every length you need in a single run.
Put your own video URL in SOURCE and your lengths in LENGTHS to try it.
Start with a free Shotstack account: copy your API key and loop your first video.
Frequently asked questions (FAQs)
Can I loop only part of a video?
Yes. Give every copy the same trim, which is where the part begins in the source, and set length to how long the part runs. Then space the copies by that length and not by the whole video’s.
How do I hide the jump when the end doesn’t match the start?
Play the clip forward and then backwards. The end of each pass is the start of the next, so the loop always joins. Our guide on how to create a boomerang video with Python builds it.
What if the soundtrack is shorter than the clip?
The video is cut to the soundtrack’s length. With a 27.38 second clip and the 21.5 second voiceover, the script places one copy, 21.498 seconds long, and the result is 21.50 seconds.