[파이썬] pydub 오디오 페이드인 및 페이드아웃

When creating audio files or working with audio tracks in Python, it is often desirable to add fades at the beginning or end of the audio. Fades can help smooth transitions, reduce abrupt changes, and make the audio sound more professional. In this blog post, we will explore how to accomplish audio fade-in and fade-out effects using the pydub library in Python.

Installing pydub

Before we begin, let’s make sure that pydub is installed. Open your terminal or command prompt and run the following command:

pip install pydub

Fade-In Effect

To add a fade-in effect to an audio track, we will gradually increase the volume from silence to the desired level. Here’s an example of how to accomplish this using pydub:

from pydub import AudioSegment

# Load audio file
audio = AudioSegment.from_file("input.wav", format="wav")

# Define fade duration in milliseconds
fade_duration = 2000  # 2 seconds

# Apply fade-in effect
audio_fadein = audio.fade_in(fade_duration)

# Export the modified audio
audio_fadein.export("output_fadein.wav", format="wav")

In the above code, we first load the audio file using the AudioSegment.from_file() method. We then specify the duration of the fade-in effect in milliseconds (2 seconds in this example). Finally, we apply the fade-in effect using the fade_in() method and export the modified audio to a new file.

Fade-Out Effect

The fade-out effect is similar to the fade-in effect, but the volume gradually decreases from the desired level to silence. Here’s an example of how to achieve this using pydub:

from pydub import AudioSegment

# Load audio file
audio = AudioSegment.from_file("input.wav", format="wav")

# Define fade duration in milliseconds
fade_duration = 2000  # 2 seconds

# Apply fade-out effect
audio_fadeout = audio.fade_out(fade_duration)

# Export the modified audio
audio_fadeout.export("output_fadeout.wav", format="wav")

In this code snippet, we follow a similar process as before. We load the audio file, specify the fade duration, apply the fade-out effect using the fade_out() method, and export the modified audio to a new file.

Conclusion

Adding fade-in and fade-out effects to audio tracks can greatly enhance the listening experience and make the transitions smoother. With the pydub library, accomplishing these effects in Python becomes straightforward and efficient. Feel free to experiment with different fade durations and combine them with other audio editing techniques to create unique audio compositions.

Remember to install pydub using pip install pydub before implementing the examples provided above. Happy coding!