Skip to content

How to Convert All WAV Files to MP3 using Python

Audio file formats play a crucial role in various applications, and sometimes you may need to convert between different formats to meet specific requirements. In this tutorial, we’ll explore how to convert a collection of WAV files to the MP3 format using Python.

Introduction

WAV and MP3 are two common audio file formats, each with its own advantages and use cases. WAV files offer uncompressed audio, making them suitable for high-quality recordings or audio editing tasks. On the other hand, MP3 files are compressed, resulting in smaller file sizes and making them ideal for online streaming and distribution.

Understanding the Code

We’ll be using Python along with the pydub library to perform the conversion.

Step 1: Installing Required Libraries

Ensure you have the pydub library installed. You can install it via pip:

pip install pydub

Step 2: Importing Necessary Libraries

import os
from pydub import AudioSegment

We import the necessary libraries:

  • os for file operations.
  • AudioSegment from pydub for audio manipulation.

Step 3: Converting WAV to MP3

def wav_to_mp3(wav_file):
sound = AudioSegment.from_wav(wav_file)
mp3_file = os.path.splitext(wav_file)[0] + ".mp3"
sound.export(mp3_file, format="mp3")
print(f"Converted {wav_file} to {mp3_file}")

def convert_all_wav_to_mp3():
wav_files = [f for f in os.listdir() if f.endswith(".wav")]

for wav_file in wav_files:
wav_to_mp3(wav_file)

Here, the wav_to_mp3 function takes a WAV file path, reads the audio, and exports it as an MP3 file. The convert_all_wav_to_mp3 function finds all WAV files in the current directory and converts them to MP3 one by one.

Step 4: Running the Conversion

if __name__ == "__main__":
convert_all_wav_to_mp3()

By running this script, all WAV files in the current directory will be converted to MP3.

Conclusion

In this tutorial, we’ve learned how to convert a collection of WAV files to the MP3 format using Python. This conversion process can be useful for various purposes such as reducing file sizes, preparing audio for online distribution, or ensuring compatibility with different devices and platforms.

Experiment with different audio file formats and explore the capabilities of Python libraries like pydub to efficiently handle audio conversion tasks.

Happy coding!