[파이썬] pydub 오디오 녹음 기능

PyDub is a powerful audio processing library for Python that allows you to perform various audio operations, including recording audio. In this blog post, we will explore how to use PyDub to record audio in Python.

Setting Up PyDub

Before we can start recording audio with PyDub, we need to make sure that we have PyDub installed on our system. You can easily install PyDub using pip by running the following command:

pip install pydub

Once PyDub is installed, we can proceed with recording audio.

Recording Audio

To record audio using PyDub, we need to use the AudioSegment class. This class represents an audio segment, which can be either loaded from a file or created from scratch. We can create an empty audio segment and append audio data to it to record audio.

Here’s an example that demonstrates how to record audio using PyDub:

from pydub import AudioSegment
import pyaudio

# Set the audio parameters
sample_rate = 44100
channels = 2
audio_format = pyaudio.paInt16

# Initialize the PyAudio object
audio = pyaudio.PyAudio()

# Start recording
stream = audio.open(format=audio_format, channels=channels, rate=sample_rate, input=True,
                    frames_per_buffer=1024)

# Create an empty audio segment
audio_segment = AudioSegment.empty()

# Record audio for 5 seconds
recording_time = 5 * 1000  # convert to milliseconds
frames_per_buffer = 1024

for i in range(int(sample_rate / frames_per_buffer * recording_time / 1000)):
    data = stream.read(frames_per_buffer)
    audio_segment += AudioSegment(data)

# Stop recording
stream.stop_stream()
stream.close()
audio.terminate()

# Save the recorded audio to a file
audio_segment.export("recorded_audio.wav", format="wav")

In the above example, we first set the audio parameters such as sample rate, number of channels, and audio format. We then initialize the PyAudio object and open a stream to start recording audio.

We create an empty AudioSegment object and continuously read audio data from the stream in chunks of 1024 frames. We append the audio data to the AudioSegment object until we have recorded the desired duration of 5 seconds.

After recording, we stop the stream, close it, and terminate the PyAudio object. Finally, we export the recorded audio to a WAV file named “recorded_audio.wav”.

Summary

In this blog post, we discussed how to use PyDub to record audio in Python. We covered the basics of setting up PyDub, initializing PyAudio, and recording audio using the AudioSegment class. Using PyDub, you can easily incorporate audio recording functionality into your Python applications.