[파이썬] pydub 오디오 빈도 분석

Have you ever wondered how to analyze the frequency of an audio file using Python? Well, look no further - in this blog post, we will explore how to use the PyDub library to perform audio frequency analysis.

PyDub is a powerful library for audio processing in Python. It provides a simple and intuitive API for manipulating audio files. One of its key features is the ability to extract the frequency information from an audio file.

Let’s dive into the code and see how we can analyze the frequency of an audio file using PyDub:

from pydub import AudioSegment
import numpy as np
import matplotlib.pyplot as plt

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

# Extract the raw audio data and convert it to a NumPy array
audio_data = np.array(audio_file.get_array_of_samples())

# Compute the Fast Fourier Transform (FFT) to obtain the frequency spectrum
freq_spectrum = np.fft.fft(audio_data)

# Get the frequencies corresponding to each point in the spectrum
frequencies = np.fft.fftfreq(len(freq_spectrum), d=1 / audio_file.frame_rate)

# Plot the frequency spectrum
plt.plot(frequencies, np.abs(freq_spectrum))
plt.xlabel('Frequency (Hz)')
plt.ylabel('Amplitude')
plt.title('Frequency Spectrum')
plt.grid(True)
plt.show()

In the code above, we first load the audio file using AudioSegment.from_file() function from PyDub. We then convert the audio data to a NumPy array using get_array_of_samples(). Next, we apply the Fast Fourier Transform (FFT) on the audio data to obtain the frequency spectrum.

The fftfreq() function from NumPy is used to get the frequencies corresponding to each point in the spectrum. Finally, we plot the frequency spectrum using matplotlib.pyplot and display it using plt.show().

By running this code with your own audio file, you can visualize the frequency spectrum and gain insights into the audio’s frequency content. This can be useful for tasks such as music analysis, speech recognition, or sound effect processing.

In conclusion, PyDub makes audio frequency analysis in Python simple and straightforward. It provides a convenient API to manipulate audio files and extract useful information such as frequency spectrum. With its ease of use and powerful capabilities, PyDub is a great choice for any audio processing task.

Give it a try and start exploring the world of audio frequency analysis with PyDub!