콘텐츠로 건너뛰기

Python으로 MP3를 WAV로 변환하는 방법

[

Converting audio to the right format

Python provides various libraries that allow us to work with audio files and perform different operations on them. In this tutorial, we will learn how to convert audio files from one format to another using the PyDub library in Python. Specifically, we will focus on converting MP3 files to WAV format.

Step 1: Installation

Before we can start working with audio files in Python, we need to install the necessary libraries. Open your command line interface and run the following command to install PyDub:

pip install pydub

We also need to ensure that we have FFmpeg installed on our system. FFmpeg is a command-line tool used for handling multimedia data and supports various audio and video formats. You can download FFmpeg from the official website (https://ffmpeg.org/) and follow the installation instructions for your operating system.

Step 2: Importing the required libraries

To begin, let’s import the necessary libraries in our Python script:

from pydub import AudioSegment

Step 3: Converting the audio file

Now, let’s create a helper function called convert_to_wav that will take a file path as input and convert the audio file from a non-WAV format to WAV format. In this example, we will convert the file call_1.mp3 from MP3 to WAV format.

def convert_to_wav(filename):
# Load the audio file
audio = AudioSegment.from_file(filename)
# Set the export format to WAV
export_format = "wav"
# Export the audio file in WAV format
audio.export(f"{filename.split('.')[0]}.{export_format}", format=export_format)

In the above code, we first load the audio file using the AudioSegment.from_file() function. Then, we set the export format to WAV using the export_format variable. Finally, we export the audio file in the WAV format using the export() function and save it with a new file name.

Step 4: Converting the example audio file

To convert the example audio file call_1.mp3 from MP3 to WAV format, we can simply call the convert_to_wav() function and pass the file path as an argument:

convert_to_wav("call_1.mp3")

This will convert the call_1.mp3 file to call_1.wav in the same directory.

Conclusion

In this tutorial, we learned how to convert audio files from MP3 to WAV format using the PyDub library in Python. Converting audio files to the appropriate format is often a necessary step before performing further operations such as transcription or analysis.