[파이썬] pydub 오디오 볼륨 조절

In this blog post, we will explore how to adjust the volume of audio files using PyDub, a powerful audio processing library for Python. Whether you want to amplify the sound or reduce it to a lower level, PyDub provides an easy-to-use interface to accomplish these tasks.

Installing PyDub

Before we can get started, we need to install PyDub. You can install it using pip by running the following command:

pip install pydub

Loading and Playing an Audio File

To adjust the volume of an audio file, we first need to load the file into our Python script. PyDub supports various audio formats such as WAV, MP3, and FLAC. Let’s load an audio file named “example.wav” as an example:

from pydub import AudioSegment

audio = AudioSegment.from_file("example.wav")

Once we have loaded the audio file, we can play it and listen to its contents using the play() function:

audio.play()

Adjusting the Volume

PyDub provides the + and - operators to increase or decrease the volume of an audio segment, respectively. These operators automatically handle clipping and normalize the audio to avoid distortion.

Let’s increase the volume by 3 decibels:

louder_audio = audio + 3
louder_audio.export("louder_example.wav", format="wav")

And now, let’s decrease the volume by 2 decibels:

quieter_audio = audio - 2
quieter_audio.export("quieter_example.wav", format="wav")

Normalizing the Volume

If you want to normalize the volume of an audio file, PyDub provides the normalize() method. This method adjusts the volume so that the highest peak in the audio reaches a specified level, usually 0 dB.

Let’s normalize the audio file to 0 dB:

normalized_audio = audio.normalize()
normalized_audio.export("normalized_example.wav", format="wav")

Conclusion

In this blog post, we learned how to adjust the volume of audio files using PyDub in Python. We explored how to load and play audio files, as well as increase, decrease, and normalize the volume. PyDub makes it easy to perform various audio processing tasks and opens up endless possibilities for working with audio in Python.

Give it a try and start experimenting with audio volume manipulation in your own Python projects!