In this tutorial, I am going to be showing you how to convert mp4 files to mp3, using python. In order to do this, we’re going to be using the MoviePy library in python, and it’s only going to take about three lines of code. Yes! Three lines of code. That’s the beauty of python for a lazy programmer😁.
Let’s begin.
What is MoviePy
MoviePy is a Python library for video editing, manipulation, and processing. It provides an easy way to work with video files, which makes it a valuable tool for tasks such as video editing, creating video clips, adding text and effects to videos, and much more.
Things you can do with MoviePy
Using MoviePy, You can do the following:
- Combine two or more video clips together to create a longer video clip.
- Add audio to videos
- Extract audio from video
- Create animations and transitions
- Crop/trim videos
- Create video Collages
- Create GIFs
- Reverse video clips
- Add text over videos
Installing MoviePy
In order to convert mp4 files to mp3, we’re first going to need the MoviePy library on our computer. So run the following command to install it:
> pip install MoviePy
Note: MoviePy depends on the following libraries: Numpy, imageio, Decorator, and tqdm. As a result, it may take some time to install MoviePy, as the installation will also include these dependencies.
Import the necessary module
The only thing we need is the VideoFileClip
constructor. This constructor enables us create a new instance of a video file in our code. So what that means is that, it lets us load in our video file from a directory in our computer.
This is how you import VideoFileClip
from MoviePy.editor import VideoFileClip
Load the mp4 file
Using the VideoFileClip
constructor, we would load our video file and store it in the video
variable.
video = VideoFileClip("example.mp4")
where example.mp4
is the filename and the format of the video you want to convert.
VideoFileClip
takes as argument, the relative file path to the video file you want to convert. In our example, example.mp4
is in the same directory as our python script. If you have your video file at a different directory from your python script, you’ll have to specify it’s path relative to where your python script is.
Extract audio from video
Then, we are going to extract the audio from the video and save it with our desired filename.
video.audio.write_audiofile("example.mp3")
where example.mp3
is the filename and the format of the audio that would be extracted from example.mp4
.
Final code
from moviepy.editor import VideoFileClip
# Load the mp4 file
video = VideoFileClip("example.mp4")
# Extract audio from video
video.audio.write_audiofile("example.mp3")
So if you’ve done everything correctly, and run your code, you should see your conversion in progress in your terminal.
PS: Don’t make my mistake. I tried extracting audio from a silent video and encountered an error.