[파이썬] pydub 오디오 파일 정보 추출

When working with audio files in Python, one of the impressive libraries is pydub. pydub provides a simple and easy-to-use interface for manipulating and working with audio files. In addition to basic audio file manipulation tasks such as slicing, concatenating, and exporting, pydub also allows you to extract various information from audio files.

In this blog post, we will focus on extracting information from audio files using pydub.

Installation

Before we begin, ensure that you have pydub installed. You can install it using pip:

pip install pydub

Extracting Audio File Information

To extract audio file information, we can use the AudioSegment class provided by pydub. Let’s see how we can extract the information such as duration, sample rate, and channels from an audio file:

from pydub import AudioSegment

# Load the audio file
audio = AudioSegment.from_file("sample_audio.wav")

# Extract the duration in milliseconds
duration = len(audio)

# Extract the sample rate
sample_rate = audio.frame_rate

# Extract the number of channels
channels = audio.channels

# Print the extracted information
print("Duration:", duration, "ms")
print("Sample rate:", sample_rate, "Hz")
print("Channels:", channels)

In the above code snippet, we first import the AudioSegment class from pydub. We then load the audio file using the from_file method of AudioSegment, passing the file name as the argument.

Next, we extract the duration of the audio using the len function, which gives us the length of the audio in milliseconds. We extract the sample rate of the audio using the frame_rate attribute, and the number of channels using the channels attribute.

Finally, we print the extracted information to the console.

Conclusion

Using pydub, we can easily extract various information from audio files in Python. In this blog post, we explored the extraction of duration, sample rate, and channels from an audio file. pydub provides a wide range of functionalities and is an excellent library for working with audio files in Python.

Give it a try and start exploring the world of audio manipulation with pydub!

Note: Remember to close the audio file after you are done using it to avoid possible resource leaks.

The examples provided in this blog post assume that you have a sample_audio.wav file in the same directory as your Python script. Modify the file name accordingly to match the audio file you are working with.

Please refer to the official pydub documentation for more details and advanced usage scenarios.