Contents
An MP3 file holds sound and no video. An MP4 video needs both, so converting MP3 to MP4 really means adding a picture and saving the two together.
YouTube needs that picture. Its page on supported file formats says: “Audio files, like MP3, WAV, or PCM files, can’t be uploaded to create a YouTube video.”
This guide shows how to turn an MP3 and one image into an MP4 with Python and Shotstack’s video editing API. The video comes out as long as the audio.
TL;DR
- An edit with two clips does the job: an audio clip and an image clip.
- Set the audio clip’s
lengthto"auto"and the image clip’slengthto"end". The video is then as long as the audio, and you don’t have to know the length first. - The script below turned an 80.20 second MP3 into an 80.20 second MP4 at 1280 x 720.
- A still picture doesn’t need 25 frames a second. At 12 fps the same video was 26.1 MB, down from 44.2 MB.
How an MP3 becomes an MP4
The Edit API renders a timeline that you describe in JSON. For this job the timeline has two tracks:
- An image clip. It shows the picture for the whole video.
"fit": "cover"makes the image fill the frame. - An audio clip. It plays the MP3 from start to finish.
Two length values save you from measuring the file. "auto" makes a clip as long as its own file, so the audio clip takes the length of the MP3. "end" makes a clip last until the timeline ends, so the image stays up until the audio stops. The smart clips guide covers both values.
Convert MP3 to MP4 with Python
The script below uses an 80 second music track and a photo of a forest path, both hosted by Shotstack. It prints the length of the audio, renders the video, and prints the length of the result.
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"
AUDIO = f"{ASSETS}/music/unminus/ambisax.mp3"
IMAGE = f"{ASSETS}/images/woods1.jpg"
FPS = 25
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 kinds of stream in a file at a URL."""
encoded = urllib.parse.quote(url, safe="")
metadata = call(f"{API}/probe/{encoded}")["response"]["metadata"]
kinds = sorted({stream["codec_type"] for stream in metadata["streams"]})
return float(metadata["format"]["duration"]), kinds
def build_edit(audio_url, image_url):
audio = {
"asset": {"type": "audio", "src": audio_url},
"start": 0,
"length": "auto",
}
image = {
"asset": {"type": "image", "src": image_url},
"start": 0,
"length": "end",
"fit": "cover",
}
return {
"timeline": {"tracks": [{"clips": [image]}, {"clips": [audio]}]},
"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.")
seconds, kinds = probe(AUDIO)
print(f"Audio: {seconds:.2f} s")
render_id = call(f"{API}/render", build_edit(AUDIO, IMAGE))["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')}")
seconds, kinds = probe(status["url"])
print(f"Video: {seconds:.2f} s, streams: {', '.join(kinds)}")
print(status["url"])Run python mp3_to_mp4.py. It prints the audio length, the render ID, the video length and the URL of the MP4:
Audio: 80.20 s
Render queued: 52c496a7-ea9e-41b7-8379-08db3e0fa28d
Video: 80.20 s, streams: audio, video
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/35tqpmb0ya/52c496a7-ea9e-41b7-8379-08db3e0fa28d.mp4This is the video from that run:
How the script works
probe()sends a file’s URL to the Probe endpoint. It returns the duration and the kinds of stream in the file.build_edit()puts the image on the top track and the audio on the track below, with the"end"and"auto"lengths described above.- The main block posts the edit and checks the render every five seconds until it is done.
- It then probes the finished file. The result has an audio stream and a video stream, and the same length as the MP3.
The script probes the MP3 only to print its length. The render doesn’t need it.
What the MP4 contains
This is what ffprobe reports for the source and the finished file:
| Source MP3 | Finished MP4 | |
|---|---|---|
| Length | 80.20 s | 80.20 s |
| Video | None. The file holds sound and a cover image | H.264, 1280 x 720, 25 fps |
| Sound | MP3, 44.1 kHz, stereo | AAC, 48 kHz, stereo |
The sound is encoded again as AAC. Our guide to audio sample rate for video explains the move from 44.1 kHz to 48 kHz.
Make the file smaller
A video of one still picture repeats the same frame, so a high frame rate adds size and nothing you can see. Here is the same edit at two frame rates:
FPS | File size |
|---|---|
| 25 | 44.2 MB |
| 12 | 26.1 MB |
Set FPS = 12 at the top of the script when the picture doesn’t move. The audio track has the same format in both files.
Change the picture
- Use your own image. Put its URL in
IMAGE. Use a JPG or PNG that is at least as large as the output, which is 1280 x 720 here. - Make a vertical video. Add
"aspectRatio": "9:16"to theoutputfor a 720 x 1280 video. With"fit": "cover", the image is cropped to fill the tall frame. - Add a title. Put a text clip on a track above the image. Our guide on how to add text to a video shows the options.
- Show a waveform. For podcasts, our article on podcast templates with waveforms adds a moving waveform to the picture.
Convert your audio to video with Shotstack
You now have a script that converts an MP3 to an MP4 with one image and one API request. Put your own URLs in AUDIO and IMAGE and run it again. The video will be as long as your audio.
Create a free Shotstack account to get your API key and convert your first file.
Frequently asked questions (FAQs)
Can I convert many MP3 files at once?
Yes. Call build_edit() once for each file and post every edit before you wait for the results. Our guide on how to bulk create videos from a CSV shows the loop with a spreadsheet of URLs.
Does this work with WAV files?
Yes. Put the WAV file’s URL in AUDIO. The audio asset reads WAV files the same way it reads MP3.
Can the picture be made for me?
Yes. Our guide on how to turn audio into a video with an AI generated image transcribes the audio, writes an image prompt from it, and generates the picture in the same render.
How do I check that the MP4 has both sound and video?
Run ffprobe -v error -show_entries stream=codec_type,codec_name -of csv=p=0 output.mp4. For the video from the script it prints h264,video and aac,audio. The script’s last line shows the same thing through the Probe endpoint: streams: audio, video.