This blog post will explain how to create a graphical frontend for ffmpeg with Python, The tkinter library will be used to create the graphical user interface that is wrapped around the ffmpeg command. There was a blog post recently written about creating a video from an audio file and still image. That is the example that is being used for this blog post.
The tkinter library is imported so that a graphical user interface can be coded. The filedialog library from tkinter has to be imported because it will be used to create three file dialog boxes. The os library has to be imported so a command can be used to run ffmpeg from a python script.
import tkinter as tk
from tkinter import filedialog as fd
import os
A tkinter object is created and stored in the variable root.
root = tk.Tk()
The statement below will hide the main window since load and save file dialogs don’t need the window.
root.withdraw()
The filetypes variable is set to two audio file extensions.
filetypes = (
('mp3', '*.mp3'),
('m4a', '*.m4a')
)
The function askopenfilename will retrieve a file name and store it in the variable filename1.
filename1 = fd.askopenfilename(
title='Open a music file.',
initialdir='/',
filetypes=filetypes)
The filetypes variable is set to two image file extensions.
filetypes = (
('png', '*.png'),
('jpg', '*.jpg')
)
The function askopenfilename will retrieve a file name and store it in the variable filename2.
filename2 = fd.askopenfilename(
title='Open an image.',
initialdir='/',
filetypes=filetypes)
The function asksaveasfilename will retrieve a file name and store it in the variable output.
output = fd.asksaveasfilename(
title="Save Output File As",
defaultextension=".mp4",
filetypes=[("MP4 Video", "*.mp4")]
)
The os.system statement will run the ffmpeg command. The -loop flag will loop the image over the song in the video. The -r flag will set the framerate of the video. The -c:a copy flag will copy the audio to the video file. The -shortest flag will end encoding of the video once the song is over.
os.system(f'ffmpeg -loop 1 -r 1 -i "{filename2}" -i "{filename1}" -c:a copy -shortest "{output}"')
The root object is destroyed.
root.destroy()
A main loop is executed for the program.
root.mainloop()
This is what the whole source code looks like.
import tkinter as tk
from tkinter import filedialog as fd
import os
root = tk.Tk()
root.withdraw()
filetypes = (
('mp3', '*.mp3'),
('m4a', '*.m4a')
)
filename1 = fd.askopenfilename(
title='Open a music file.',
initialdir='/',
filetypes=filetypes)
filetypes = (
('png', '*.png'),
('jpg', '*.jpg')
)
filename2 = fd.askopenfilename(
title='Open an image.',
initialdir='/',
filetypes=filetypes)
output = fd.asksaveasfilename(
title="Save Output File As",
defaultextension=".mp4",
filetypes=[("MP4 Video", "*.mp4")]
)
os.system(f'ffmpeg -loop 1 -r 1 -i "{filename2}" -i "{filename1}" -c:a copy -shortest "{output}"')
root.destroy()
root.mainloop()