Friday, January 5, 2024

Extract audio from video using python

Extracting Audio from Video Using Python and MoviePy

Extract audio from video using python


Handling the video in its raw binary format will become complicated, and for this purpose, we will make use of an external library called MoviePy. MoviePy can read and write all the most common audio and video formats, including GIF, and runs on various operating systems such as Windows, Linux, and macOS, with Python version 2.7 and above.

1. Install MoviePy Library

This library does not come inbuilt, so we need to install it using the package manager pip. To install the MoviePy Library, open the terminal and write the following command:

pip install moviepy

2. Import MoviePy Library

Now, let’s get started by importing the libraries. We need to import the MoviePy package or the editor class alone specifically.

# Import MoviePy
import moviepy.editor
    

3. Load the Video

Before moving to the next step, let’s learn about video formats. We should know our video’s format to do the conversion without any problem. Create a VideoFileClip object by referencing the video file through the parameter.

# Load the Video Clip
video = moviepy.editor.VideoFileClip("Video.mp4")
    

4. Extract the Audio

Besides the video format, it’s also a good practice to know some audio formats. Now, we have some ideas about both formats. It’s time to do the conversion using the MoviePy library.

We will now extract the audio of the video that we defined. 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.

# Extract and export the Audio
video.audio.write_audiofile("Audio.mp3")
    

We will convert the video to MP3 format, it is the most common one. Depending on the requirement, we can change the format. For example, while using audio for speech recognition, the WAV format works better.

# Import MoviePy
import moviepy.editor

# Load the Video
video = moviepy.editor.VideoFileClip("Video.mp4")

# Extract the Audio
audio = video.audio

# Export the Audio
audio.write_audiofile("audio.mp3")
    

With these steps, you can effortlessly extract audio from a video using Python and the MoviePy library.


Incoming search terms:-
  • How to convert video to audio using Python
  • How to extract audio from video using python
  • How to extract mp3 from mp4 using python
  • How to extract audio from YouTube shorts using python
  • How to extract audio from Instagram reel using python


Extract audio from video using python