DEV Community

Cover image for How to extract an audio file from a video with Python

Posted on • Updated on • Originally published at

How to extract an audio file from a video with Python

Before finding working Python code for the purpose of this post, I thought it would be easy to find working examples. But, it was not and that is the reason I write this post.

If I do not know how to use Python or other programming languages. I would have to repeatedly wait for a software to separate an audio clip from video clip.

Then, I should compile only audio files and wait for a long time.

But I would not do that. With the power of programming, we do not have to repeat what we already know.

Before you use the code below, please read these and install Python and pip first if you haven't yet.

The pip will be used to install and use Moviepy.

You can install it with $pip install moviepy.

  1. How to install Python

  2. How to install pip

  3. Moviepy official website

  4. sys-env in Python

1. Python Code to extract audios from the videos

I will assume you already prepared a video file with audio for this process. It is very simple and you can use the code below with it.

# Create a file with 
# $touch

# 1.
import sys
from moviepy.editor import *

video = VideoFileClip(sys.argv[1]) # 2.
audio = # 3.
audio.write_audiofile(sys.argv[2]) # 4.
Enter fullscreen mode Exit fullscreen mode

You can save this code with file and test it with the command below.

$python <video_file> <audio_file>
Enter fullscreen mode Exit fullscreen mode

For example, $python video_for_audio.mp4 audio_from_video.mp4

It will make audio_from_video.mp4 file in your machine.

What we do here are

  1. We import default Python sys module to use sys.argv later and moviepy.editor to extract audio files from videos.

  2. In video = VideoFileClip(sys.argv[1]) you instruct your machine which video file you want to use to extract audio.

  3. Then, with audio =, you select audio file inside the video file. You can see that Python use . syntax for that.

  4. Lastly, with audio.write_audiofile(sys.argv[2]), You end the process and assign the result audio file name.

and that is all you need to know to extract audio from the video with python.

The sys or sys.argv here is to help you automate your work with CLI params.

What comes first after $python would be sys.argv[1] and others would be sys.argv[2] and more.

2. Conclusion

In this post, you learnt you don't need any software to extract an audio file from video and use Python instead.

You can follow me at GitHub.

You can contact or hire me at Telegram.

Thanks and please share this post with others.

Top comments (0)