How to convert audio WAV to MP3 in Python?


Python - Convert wav to mp3

In this tutorial, you shall learn how to convert a given .wav audio file to .mp3 audio file using pydub library in Python.

Prerequisites

You must have pydub and FFmpeg installed in your system.

Refer Install pydub.

Step to convert .wav to .mp3 using pydub

1. Import AudioSegment

We have to import AudioSegment class from pydub package.

from pydub import AudioSegment

2. Create AudioSegment

We have to create AudioSegment from given input audio file. Since the input audio is in WAVE format, we have to call from_wav() method of the AudioSegment class, and pass the path of given input audio file as string argument.

audio = AudioSegment.from_wav(input_audio_file)

3. Export AudioSegment

We can export the AudioSegment created in the previous step to an output file in a specified format.

Since our task is to convert given WAVE audio file to MP3 file, all we have to do is, call export() method on the AudioSegment object, pass the required output file name as first argument, and the format as mp3.

audio.export(output_audio_file, format="mp3")

Python Program to Convert .wav to .mp3

Assuming that you installed the pydub and FFmpeg libraries, we shall write a Python program, using the above steps, that converts the given WAV file input.wav to an MP3 file output.mp3.

Python Program

from pydub import AudioSegment

# Convert wav to mp3                                                            
audio = AudioSegment.from_wav("input.wav")
audio.export("output.mp3", format="mp3")
print('Success. Given audio converted to mp3.')

Output

Success. Given audio converted to mp3.

A new audio file output.mp3 should be created.

Summary

In this Python pydub tutorial, we have seen the steps to convert a given WAVE audio file to an MP3 file in Python, using pydub library, with example program.