Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

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.

Easy Python 3.9+ Jun 27, 2026 Files & data 1 views 0 copies

Requires third-party packages — install first
pip install pyaudio

Python code

37 lines
Python 3.9+
import 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

stdout
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

  1. Use `p.open(input_device_index=...`) to select a specific microphone instead of the default.
  2. 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

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Files & data

Related tutorials and quizzes for this topic.