How to extract audio from video in Python
In this article, we will discuss how to extract audio from a video in Python. You may need this as a feature of your project or for automating tasks using Python scripts.
moviepy library to handle video
Handling the video in its raw binary format will become complicated and hence for this purpose, we will make use of an external library called moviepy. This does not come inbuilt and hence we need to install and we will use the package manager pip for this purpose.
The below code can be used to install moviepy
pip install moviepy
To test if the package has been installed correctly, run the following code on your Python shell.
If no errors show up, you are good to proceed further.
Python program to extract audio from video
Once we are done with the installation of the packages, we are already done with most of the work.
We need to import the moviepy package or the editor class alone specifically. Then we need to create a VideoFileClip object by referencing the video file through the parameter.
import moviepy.editor # Replace the parameter with the location of your file video = moviepy.editor.VideoFileClip("G:\Python37\sample.avi")
Once this is done, extracting the audio is as simple as accessing the audio member of the VideoFileClip object that we created. Then we have to write the extracted audio into a different file whose filename has to be specified.
The final code looks as follows
import moviepy.editor # Replace the parameter with the location of the video video = moviepy.editor.VideoFileClip("G:\Python37\sample.avi") audio = video.audio # Replace the parameter with the location along with filename audio.write_audiofile("G:\Python37\sample.mp3")
I hope this article was helpful for you in extracting audio from video using a python script.