How to get PyAudio to continuously record?

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To continuously record audio using PyAudio, you can create a loop that continuously reads audio frames from the input stream. Here's an example code snippet that demonstrates how to achieve this:

python
import pyaudio

# Configuration
chunk_size = 1024 # Number of frames per buffer
sample_format = pyaudio.paInt16 # 16-bit audio
channels = 1 # Mono input
sample_rate = 44100 # Sample rate (Hz)

# Initialize PyAudio
audio = pyaudio.PyAudio()

# Open the audio stream
stream = audio.open(
format=sample_format,
channels=channels,
rate=sample_rate,
frames_per_buffer=chunk_size,
input=True
)

# Continuously record audio
print("Recording started. Press Ctrl+C to stop.")
try:
while True:
data = stream.read(chunk_size)
# Process the recorded audio data here
# For example, you can write the data to a file or perform real-time analysis
except KeyboardInterrupt:
print("Recording stopped.")

# Stop and close the audio stream
stream.stop_stream()
stream.close()

# Terminate PyAudio
audio.terminate()

This code sets up a PyAudio stream for recording audio. Inside the loop, it continuously reads audio frames from the stream using stream.read() with the specified chunk_size (number of frames per buffer). You can process the recorded audio data inside the loop according to your requirements, such as writing the data to a file or performing real-time analysis.

To stop the recording, you can interrupt the loop by pressing Ctrl+C, which raises a KeyboardInterrupt exception. The code handles this exception and stops the recording gracefully.

Make sure you have the pyaudio module installed. You can install it using pip with the command pip install pyaudio.

Feel free to modify the code to suit your specific needs, such as adjusting the sample format, channels, sample rate, or performing additional processing on the recorded audio data.