Recording Audio with Python Using PvRecorder
This tutorial explains how to install the PvRecorder library, list available microphones, capture audio streams with configurable frame length, and optionally save the recorded data to a WAV file using Python, providing complete code examples for each step.
In this guide we demonstrate how to use Python to record audio with the pvrecorder library. First, install the library via pip:
<code>pip3 install pvrecorder</code>Next, list all available audio devices to identify the microphone you want to use:
<code>from pvrecorder import PvRecorder
for index, device in enumerate(PvRecorder.get_audio_devices()):
print(f"[{index}] {device}")</code>Note the index of the desired microphone; you can also use -1 to select the default device.
To start recording, create a PvRecorder instance with the chosen device_index and a frame_length (e.g., 512 samples for 32 ms at 16 kHz). Then call start() , repeatedly read frames with read() , and finally stop and delete the recorder:
<code>recorder = PvRecorder(device_index=-1, frame_length=512)
try:
recorder.start()
while True:
frame = recorder.read()
# Do something with the frame ...
except KeyboardInterrupt:
recorder.stop()
finally:
recorder.delete()</code>If you want to save the captured audio to a WAV file, accumulate the frames in a list and write them using the wave module:
<code>from pvrecorder import PvRecorder
import wave, struct
recorder = PvRecorder(device_index=-1, frame_length=512)
audio = []
try:
recorder.start()
while True:
frame = recorder.read()
audio.extend(frame)
except KeyboardInterrupt:
recorder.stop()
with wave.open('audiotest.wav', 'w') as f:
f.setparams((1, 2, 16000, 512, "NONE", "NONE"))
f.writeframes(struct.pack('h' * len(audio), *audio))
finally:
recorder.delete()</code>These steps allow you to capture microphone input, process it in real time, and store it for later analysis or playback.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.