How to Record Audio from Your Microphone in Python
Record audio from your default microphone using PyAudio and save it as a WAV file with a simple reusable function.
pip install pyaudio
Python code
37 linesimport pyaudio
import wave
def record_audio(filename: str, duration: int = 5, sample_rate: int = 44100, chunk: int = 1024):
"""Record audio from default microphone and save as WAV file."""
audio_format = pyaudio.paInt16 # 16-bit resolution
channels = 1 # Mono
p = pyaudio.PyAudio()
stream = p.open(format=audio_format,
channels=channels,
rate=sample_rate,
input=True,
frames_per_buffer=chunk)
print(f"Recording for {duration} seconds...")
frames = []
for _ in range(0, int(sample_rate / chunk * duration)):
data = stream.read(chunk)
frames.append(data)
print("Recording finished.")
stream.stop_stream()
stream.close()
p.terminate()
with wave.open(filename, 'wb') as wf:
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(audio_format))
wf.setframerate(sample_rate)
wf.writeframes(b''.join(frames))
print(f"Audio saved to {filename}")
if __name__ == "__main__":
record_audio("my_recording.wav", duration=3) # Quick 3-second demo
Output
Recording for 3 seconds...
Recording finished.
Audio saved to my_recording.wav
How it works
The pyaudio.PyAudio() object manages audio hardware. Opening a stream with input=True captures from the default microphone. Reading chunks in a loop collects raw audio data, which is then written to a WAV file using Python's standard wave module. The sample rate and bit depth (16-bit, mono) are chosen for compatibility with most systems. Always close the stream and terminate PyAudio to release hardware resources.
Common mistakes
- Forgetting to install PortAudio system library (e.g., via `brew install portaudio` on macOS or `apt install portaudio19-dev` on Ubuntu) before installing PyAudio.
- Not stopping the stream or calling `p.terminate()`, which can leave the microphone locked.
- Using an incorrect chunk size that causes buffer underflows or clicks in larger recordings.
Variations
- Use `p.open(input_device_index=...`) to select a specific microphone instead of the default.
- Use a threaded approach or `pyaudio.paCallback` for non-blocking, real-time streaming.
Real-world use cases
- Building a voice memo app that records short notes and stores them as local audio files.
- Creating a simple audio logger for meetings or lectures with timestamps.
- Prototyping a voice-controlled assistant that captures user commands for offline processing.
Sponsored
More from Files & data
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
- Compare Two Folder Structures and Find Differences in Python easy
- Compress and Extract ZIP Files Programmatically in Python easy
- Convert CSV Files to JSON in Python easy
- Convert Image to ASCII Art in Python medium
Keep learning
Related tutorials and quizzes for this topic.