How to extract audio from video in Python

·

2 min read

Extracting audio from a video file is a common task that can be accomplished with various libraries in Python. This guide will walk you through the process using two popular libraries: moviepy and ffmpeg-python. Both libraries are wrappers around FFmpeg, a powerful multimedia framework that can decode, encode, transcode, mux, demux, stream, filter, and play almost anything that humans and machines have created.

Prerequisites

Before you start, ensure you have Python installed on your system. You will also need to install FFmpeg. Most of the time, installing the Python libraries will handle FFmpeg for you, but in some cases, you might need to install FFmpeg manually.

  • Python: Ensure you have Python 3.x installed.

  • FFmpeg: Check if FFmpeg is installed by running ffmpeg -version in your terminal or command prompt. If it's not installed, download and install it from FFmpeg's official website.

MoviePy

moviepy is a Python module for video editing that can cut, concatenate, and modify videos, and also handle audio.

pip install moviepy

Here's a simple script to extract audio from a video file and save it as an MP3 file:

from moviepy.editor import VideoFileClip

def extract_audio_moviepy(video_path, output_audio_path):
    video = VideoFileClip(video_path)
    audio = video.audio
    audio.write_audiofile(output_audio_path)
    audio.close()
    video.close()

video_path = 'path/to/your/video.mp4'
output_audio_path = 'path/to/your/output/audio.mp3'
extract_audio_moviepy(video_path, output_audio_path)

ffmpeg-python

ffmpeg-python provides a Pythonic wrapper around FFmpeg's command-line interface, making it easier to work with for Python developers.

pip install ffmpeg-python

Here's how you can extract audio using ffmpeg-python:

import ffmpeg

def extract_audio_ffmpeg(video_path, output_audio_path):
    (
        ffmpeg
        .input(video_path)
        .output(output_audio_path, acodec='copy')  # Use 'acodec' to specify audio codec. 'copy' means no re-encoding.
        .run()
    )

video_path = 'path/to/your/video.mp4'
output_audio_path = 'path/to/your/output/audio.mp3'
extract_audio_ffmpeg(video_path, output_audio_path)

Both methods are effective for extracting audio from video files in Python. moviepy is more straightforward and better suited for simple tasks and video editing, while ffmpeg-python offers more control and is better for more complex processing tasks.