[파이썬] pydub 오디오 분할하기

If you are working with audio files in Python and need to split them into smaller segments, pydub is a powerful library that can help you achieve this task. Pydub provides a simple and intuitive interface to work with audio files, making it easy to manipulate and process them.

In this blog post, we will explore how to use pydub to split an audio file into smaller segments. Let’s get started!

Installation

To begin, make sure you have pydub installed. You can install it using pip:

$ pip install pydub

Splitting Audio with pydub

Now that you have pydub installed, let’s see how we can split an audio file using this library. The process involves loading the audio file, specifying the start and end times of the segments, and then exporting them as separate files.

Here’s an example code to split an audio file into smaller segments:

from pydub import AudioSegment

def split_audio(input_file, output_directory, segment_duration):
    audio = AudioSegment.from_file(input_file)
    total_duration = len(audio)
    num_segments = total_duration // segment_duration

    for i in range(num_segments):
        start_time = i * segment_duration
        end_time = start_time + segment_duration
        
        segment = audio[start_time:end_time]
        segment.export(f"{output_directory}/segment_{i}.wav", format="wav")

Let’s break down the code step by step:

  1. We import the AudioSegment class from the pydub module.
  2. The split_audio function takes in the input_file, output_directory, and segment_duration as parameters.
  3. We load the audio file using AudioSegment.from_file method.
  4. We calculate the total duration of the audio file and determine the number of segments based on the specified segment_duration.
  5. Using a loop, we iterate over the segments and calculate the start and end times for each segment.
  6. We extract the segment using slicing operations on the audio object.
  7. Finally, we export each segment as a separate audio file using the export method.

To use this code, simply call the split_audio function with the appropriate arguments:

split_audio("input_audio.wav", "output_directory", 10000)  # Split into 10-second segments

Conclusion

In this blog post, we have explored how to split an audio file into smaller segments using pydub in Python. Pydub provides a convenient way to manipulate audio files and offers various other functionalities for audio processing.

Feel free to experiment with different segment durations and explore more advanced features of pydub to enhance your audio processing tasks. Happy coding!