This mini blog is about how one can extract audio files from video clips using Python! This can be done in less than 5 lines of code but what is more important is to get started with Moviepy module.
We are going to take a look at Moviepy module of python which is widely used for editing videos using python.
Moviepy makes video editing painless in python and by using just few python one-liners one can get desired outcome!
Here we are going to extract audio file from a sample video file.
I have used a sample MP4 video clip in this blog. You can use any video file.
Let's get into the coding part!
First of all we need to install moviepy module in python by typing the following command in terminal window:
pip install moviepy
The next step is to install FFmpeg module. FFmpeg is a multimedia framework used for handling audio, video and other streams.
To install FFmpeg, type the following command in the terminal window:
pip install ffmpeg
If the installation was successful then you are all set up!
We will begin by importing the moviepy module:
import moviepy.editor as mp
The next step is to copy the sample video in the project folder and define the video file in python code. Moviepy comes with a handy
VideoFileClip() method that imports the sample video as a moviepy object. Here is how you can import the video file inside the python code:
video = mp.VideoFileClip(r"sample.mp4") #here sample.mp4 is the name of video clip. 'r' indicates that we are reading a file
Now it's time to convert the video file into audio file. We will be converting the .mp4 file into .mp3 file. To do this add the following line in the program:
video.audio.write_audiofile(r"output.mp3") #Here 'output.mp3' is the name of the audio file
You are all done!
The final code will look like this:
import moviepy.editor as mp video = mp.VideoFileClip(r"sample.mp4") video.audio.write_audiofile(r"output.mp3")
And that's it! 🎉 Check the project folder and you will see the
output.mp3 file which has been extracted from the sample video file.
This was the first blog post about Moviepy. I will be creating more projects using it and will write blogs about them as well!
If you are stuck at any point, do let me know in the comments section or ping me in our discord server where 200+ programmers are hacking on something!