DEV Community

Jima Victor
Jima Victor

Posted on • Edited on

How to convert mp4 to mp3 using python

In this tutorial, I am going to be showing you how to convert files from mp4 to mp3, using python. In order to do this, we're going to be using the moviePy library, and it's only going to take about three lines of code. Yes! Three lines of code. That's the beauty of python as a lazy programmer๐Ÿ˜.

Let's begin.

Installing moviePy

Firstly, we're going to need the moviePy library on our computer. So run the following command to install it:

> pip install moviepy
Enter fullscreen mode Exit fullscreen mode

Import the necessary modules

from moviepy.editor import *
Enter fullscreen mode Exit fullscreen mode

Load the mp4 file

Using the VideoFileClip method, we would load our video into a variable video

video = VideoFileClip("example.mp4")
Enter fullscreen mode Exit fullscreen mode

where example.mp4 is the filename and the format of the video you want to convert.

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")
Enter fullscreen mode Exit fullscreen mode

where example.mp3 is the filename and the format of the audio extracted from example.mp4.

Final code

from moviepy.editor import *

# Load the mp4 file
video = VideoFileClip("example.mp4")

# Extract audio from video
video.audio.write_audiofile("example.mp3")
Enter fullscreen mode Exit fullscreen mode

So if you've done everything correctly, and run your code, you should see your conversion in progress in your terminal.

Top comments (3)

Collapse
 
10xlearner profile image
10x learner

Simple! Straight forward! I love it !!

Image description

Collapse
 
jimajs profile image
Jima Victor

Thank you!๐Ÿ˜€