Python Beginner Project 2021 — Desktop application: convert mp4 to mp3

Selmi Abderrahim
7 min readAug 3, 2021

Introduction

In this lecture, we will build a desktop application with Tkinter. The purpose of this app is to upload an mp4 video format and convert it into an mp3 audio format. You might see this feature online, those online video converters. But today, we will create a desktop application, not a web application.

If you are interested in learning Python, I wrote a full beginner Python tutorial, that covers all the basics you need and it contains 20 exercises with correction plus 3 other well explained projects.

So let’s get started.

The demo of the project

When I run the application, this windows pops up:

It’s our simple GUI app with a simple background image and text widget.

Let’s click the upload button and see.

Another windows will pop up:

So it’s time to get the audio of this video.

When I click on that video, there is something happening in the backend. This is the progress of the conversion.

Once it’s done, this window will pop up and tell you that everything is done. Otherwise, it will tell you if an error has occurred.

So let’s check our folder. We will find the audio file beside the mp4 file.

That’s all that this app can do.

2 — What is Tkinter

One of the reasons why Python is a powerful programming language is that Python comes with a built-in Tkinter module, which means there’s no need to bother yourself installing it.

Tkinter is free to use, so you won’t find any troubles when you publish your application built-in Tkinter. The cool thing about it is you can develop your Python GUI (Graphical User Interface) applications with only a few lines, and you will see so in the project later on.

Also, Tkinter is easy to learn and cross-platform, which means you can run it on WindowsWindows, macOS, and Linux systems.

3 — Create the backend

We are going to create a Python program that isolates the audio from a video, so the input is an mp4 video and the output should be an mp3 audio.

In order to do that, we will use the moviepy library.

MoviePy is a Python library for video editing: cutting, concatenations, title insertions, video compositing (a.k.a. non-linear editing), video processing, and creation of custom effects. See the gallery for some examples of use.

Without wasting more time, let’s jump to our text editor and create the backend of our application.

First thing, Make sure that you have moviepy installed in your machine by using the command line:

$ pip install moviepy

If you are using windows, paste it in th cmd. and press enter.

Also you need to install the ffmpeg, which is a Python FFmpeg wrapper that works well for simple as well as complex signal graphs.

$ pip install ffmpeg-python

Once we have installed what do we need, it’s time to import our library

import moviepy.editor as mp

The mp is kinda the shortcut of the moviepy.editor.

Then we declare our video clip, using the VideoFileClip() method, we kinda uploaded our video to Python to work on it.

clip = mp.VideoFileClip(“video.mp4”)

And finally, we convert our mp4 video to mp3 audio:

clip.audio.write_audiofile(“audio.mp3”)

Then, you’ll see this:

chunk: 14%|████████▍ | 2015/14025 [00:03<00:20, 588.32it/s, now=None]

Wait until it’s done. Then We get our audio file.

That’s all the story, less code, better performance.

4 — Create our GUI

To Create our new Python GUI (Graphic User Interface) app, the first thing we need to do is, create a new script, and let’s name it mp4tomp3.py.

Then, at the top of our file, we need to import the Tkinter module

from tkinter import *

Now, we create the main app window by using the Tk() method.

window = Tk()

And we give it a title by using the title() method, applied to the window variable that we’ve created.

window.title(“Python GUI — mp4 to mp3”)

And this line of code to set the icon of our app.

window.iconbitmap(“C:/Users/cisco/Downloads/mp4tomp3.ico”)

And the last line, we use the mainloop() method to make our app ready to run.

window.mainloop()

Now, time to make our app look better.

We can start adding a label.

We need to import ttk, which we will use to add our label.

from tkinter import ttk

We will name our first label upload

upload_label = ttk.Label(window, text=”Upload your file.”)

Then, we Use the replace layout manager to choose the position of our label, for now let’s keep it in the first line.

upload_label.place(x=150, y=20)

Next, we have to add our upload button, we will use ttk too.

upload_button = ttk.Button(window, text=”Click To Upload”)

The position of the button should be beside the label

upload_button.place(x=50, y=20)

So far, our app looks like this:

And the code is the follow:

from tkinter import *from tkinter import ttkwindow = Tk()window.title(“Python GUI — mp4 to mp3”)window.iconbitmap(“mp4tomp3.ico”)upload_label = ttk.Label(window, text=”Upload your file.”)upload_label.place(x=150, y=20)upload_button = ttk.Button(window, text=”Click To Upload”)upload_button.place(x=50, y=20)window.mainloop()

I don’t like the size of the windows, let’s change it.

window.geometry(‘500x500’)

It’s time to add the backend to our app. First, we need to create a function for the button.

def action():videoname = filedialog.askopenfilename(initialdir = “/”,title = “Select file”,filetypes = ((“mp4 files”,”*.mp4"),(“all files”,”*.*”)))filename = videoname.replace(“\\”,”/”)clip = mp.VideoFileClip(filename)audio_name = filename.replace(“.mp4”,”.mp3")clip.audio.write_audiofile(audio_name)

How It Works?

First of all, we need to import some libraries

import moviepy.editor as mp

And to be able to upload our file we need to use filedialog, which allows us to get the path of the video file within our app.

from tkinter import filedialog

We need a function, so when someone clicks on this button, the conversion of the mp4 file should start.

def action():

We should make sure that the extension is mp4 and we will save the path of the file in the “filename”.

filename = filedialog.askopenfilename(initialdir = “/”,title = “Select file”,filetypes = ((“mp4 files”,”*.mp4"),(“all files”,”*.*”)))

If you’re using windows, type this to avoid a possible error of the escape character.

filename = filename.replace(“\\”, “/”)clip = mp.VideoFileClip(filename)

So we have our clip read, but before that we need to set up the name of the audio file.

audio_name = filename.replace(“.mp4”, “.mp3”)

And finally, we convert our mp4 video to mp3 audio by typing:

clip.audio.write_audiofile(audio_name)

So we have our function, we need now to bind it with the button, by doing so:

upload_button = ttk.Button(window, text=”Click To Upload”, command=action)

Let’s add another functionality, we want to see a message box that tells us if the conversion is done or an error occurred.

We do so by using the try-except-block.

try:
videoname = filedialog.askopenfilename(initialdir = “/”,title = “Select file”,filetypes = ((“mp4 files”,”*.mp4"),(“all files”,”*.*”)))
filename = videoname.replace(“\\”,”/”)
clip = mp.VideoFileClip(filename)
audio_name = filename.replace(“.mp4”,”.mp3")
clip.audio.write_audiofile(audio_name)
except:
messagebox.showwarning(title=”Error”, message=”An error has been occured!”)
else:
messagebox.showinfo(title=”Succeed”, message=”Your file has been converted successfully.”)

As you see we used the messagebox utility, which means we need to import it.

from tkinter import messagebox

Another thing we could do is add the help to text in our app, since we have enough space for it.

So first, we create a help text variable

help_text = “””
Help:
1 — Click on the upload button.
2 — Choose the video you want to upload.
3 — Wait for some seconds.
4 — You’ll find the audio within the video’s folder.
“””

Then, we create a help label.

help = ttk.Label(window, text=help_text)

And its position should be in the middle

help.place(x=20, y=50)

And finally, let’s add the logo to our app

To do so, we have to use an external library that handle our logo, which is pillow

from PIL import Image, ImageTk

To load the logo:

load = Image.open(“C:/Users/cisco/Downloads/mp4tomp3.png”)
render = ImageTk.PhotoImage(load)

Then associate it with the label:

img = Label(window, image=render)
img.image = render
img.place(x=0, y=30)

And that’s it for this project

The final code looks as follow:

from tkinter import *from tkinter import filedialogfrom tkinter import ttkimport moviepy.editor as mpfrom tkinter import messageboximport tkinterfrom PIL import Image, ImageTk#Now, we create the main app window by using the Tk() method.window = Tk()window.title(“Python GUI — Mp4 To Mp3”)window.iconbitmap(“mp4tomp3.ico”)#To load an image:load = Image.open(“mp4tomp3.png”)render = ImageTk.PhotoImage(load)#Then associate it with the label:img = Label(window, image=render)img.image = renderimg.place(x=0, y=30)upload = ttk.Label(window, text=”Upload your file.”)upload.place(x=150, y=20)def action():try:videoname = filedialog.askopenfilename(initialdir = “/”,title = “Select file”,filetypes = ((“mp4 files”,”*.mp4"),(“all files”,”*.*”)))filename = videoname.replace(“\\”,”/”)clip = mp.VideoFileClip(filename)audio_name = filename.replace(“.mp4”,”.mp3")clip.audio.write_audiofile(audio_name)except:messagebox.showwarning(title=”Error”, message=”An error has been occured!”)else:messagebox.showinfo(title=”Succeed”, message=”Your file has been converted successfully.”)upload_button = ttk.Button(window, text=”Click To Upload”, command=action)upload_button.place(x=50, y=20)help_text = “””Help:1 — Click on upload button.2 — Choose the video you want to upload.3 — Wait for some seconds.4 — You’ll find the audio within the video’s folder.“””help = ttk.Label(window, text=help_text)help.place(x=20, y=50)#I don’t like it’s size, let’s change it.window.resizable(True,True)window.geometry(‘500x500’)window.mainloop()

--

--

Selmi Abderrahim

I’m a computer science student. I do freelancing in my free time. I am a big fan of affiliate marketing, it helped me a lot to monetize my daily stuff.