In this module, we are going to code a very compact yet essential program which would help us extract audio from video or the mp3 from mp4 files. We’ll put the main functionality inside a function so that we can use it with other programs as well !
Installing Required Packages
Before we begin we need to install a package which would be required to extract audio from video files. You can simply install it with the pip package manager:
$ sudo pip3 install moviepy
That’s it and now we can go forth with our code.
Code to Extract Audio from Video files
from moviepy.editor import *
def mp4tomp3(mp4file,mp3file):
videoclip=VideoFileClip(mp4file)
audioclip=videoclip.audio
audioclip.write_audiofile(mp3file)
audioclip.close()
videoclip.close()
mp4tomp3("video.mp4","audio.mp3")
Understanding The Code
Line 1: Importing Required Libraries
from moviepy.editor import *
First, we need to import moviepy
which would help us with the conversion process. It is a very handy tool which instrumental library for video editing: cutting, concatenations, title insertions, video compositing (a.k.a. non-linear editing), video processing, and creation of custom effects.
Line 3-8: Defining Our Function
def mp4tomp3(mp4file,mp3file):
videoclip=VideoFileClip(mp4file)
audioclip=videoclip.audio
audioclip.write_audiofile(mp3file)
audioclip.close()
videoclip.close()
Here we define a function which takes in two arguments :
- mp4file: which contains the name of the mp4 file we want to convert
- mp3file: which contains the name of the resultant mp3 file as obtained from audio extraction
Then in Line 4 we load the mp4file so that we can perform required operations on it. Nextup, we simply extract the audio from the VideoClipFile object we previously created, and then store it as a file as specified by the arguments passed.
Finally, we close the handles to the the audio and video objects to prevent any unwanted errors before exiting the function.
Line 10: Calling Our Function
mp4tomp3("video.mp4","audio.mp3")
Finally call our function by providing a video name and the name of the audio file we want to store it as. This should create a file audio.mp3 in our current directory !
Convert and Extract Audio from Video Files
The moviepy
library is very portable and it it compatible across Windows, Linux and MacOS, hence it produces similar results for all.
On running our code, we should observe a little tqdm
progress bar which should disappear once the extraction process is complete. You can then play it using the music player of your choice!


Conclusion
This little piece of code can come in very handy at times. You can come it to read the function arguments from the command line itself and add the program to your PATH to have a handy system-wide available tool at your disposal !