Last modified: Apr 16, 2026 By Alexander Williams

Record Audio in Python: A Simple Guide

Recording audio is a common task. You can use it for voice assistants or data analysis. Python makes it simple.

This guide will show you how. We will use popular libraries. You will learn to capture and save sound.

Why Record Audio with Python?

Python is a great choice for audio tasks. It is easy to read and write. Many powerful libraries exist.

You can automate recordings. You can process the audio after. It integrates well with other tools.

For a broader look at handling sound, see our Python Audio Processing Guide for Beginners.

Setting Up Your Environment

First, you need to install a library. The most common one is PyAudio. It provides bindings for PortAudio.

Open your terminal or command prompt. Use pip to install it.


pip install pyaudio

On some systems, you may need extra steps. For macOS, you might need portaudio first. Use Homebrew.


brew install portaudio
pip install pyaudio

Windows and Linux users can usually install directly with pip. If you have issues, check the library documentation.

Your First Audio Recording

Let's write a simple script. It will record for a few seconds. We will use PyAudio.

We need to define some parameters. These are sample rate, channels, and chunk size.


import pyaudio
import wave

# Recording parameters
FORMAT = pyaudio.paInt16  # 16-bit resolution
CHANNELS = 1              # Mono audio
RATE = 44100              # Sample rate (44.1 kHz)
CHUNK = 1024              # Frames per buffer
RECORD_SECONDS = 5
OUTPUT_FILENAME = "output.wav"

# Initialize PyAudio
audio = pyaudio.PyAudio()

# Open stream
stream = audio.open(format=FORMAT, channels=CHANNELS,
                    rate=RATE, input=True,
                    frames_per_buffer=CHUNK)

print("Recording...")

frames = []

# Capture data in chunks
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("Finished recording.")

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

# Save the recorded data as a WAV file
waveFile = wave.open(OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()

print(f"Audio saved to {OUTPUT_FILENAME}")

Run this script. It will record 5 seconds of audio. The sound will come from your default microphone.

The file will save as "output.wav" in your current folder. You can play it with any media player.

The key function here is stream.read(). It grabs audio data from the microphone.

Using the SoundDevice Library

PyAudio can be tricky to install. An excellent alternative is SoundDevice. It is simpler and uses PortAudio.

Install it with pip.


pip install sounddevice

You also need NumPy and SciPy to save files.


pip install numpy scipy

Now, let's record with SoundDevice.


import sounddevice as sd
from scipy.io.wavfile import write

# Recording parameters
fs = 44100  # Sample rate
seconds = 5  # Duration of recording

print("Recording with SoundDevice...")
# Record audio
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=1)
sd.wait()  # Wait until recording is finished

# Save as WAV file
write("output_sd.wav", fs, myrecording)
print("Audio saved to output_sd.wav")

This code is much shorter. The sd.rec() function handles everything. It returns the audio as a NumPy array.

The sd.wait() function is crucial. It blocks the program until recording is complete.

Choosing the Right Audio Format

You saved files as WAV. It is a lossless format. The file size can be large.

You might want MP3 for smaller size. You will need an extra library like pydub or lame.

WAV is best for editing. MP3 is best for sharing. Choose based on your project needs.

To explore more libraries and formats, check our guide on Python Audio Libraries: Play, Record, Process.

Handling Common Recording Issues

You might run into problems. Here are some fixes.

No default input device found. This means PyAudio cannot see your microphone. Check your system sound settings.

You can list all devices with PyAudio.


import pyaudio
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
    info = p.get_device_info_by_index(i)
    print(f"Index {i}: {info['name']} - Input Channels: {info['maxInputChannels']}")
p.terminate()

Find your microphone index. Use that index in the stream.open() function with the input_device_index parameter.

Recording is choppy or has noise. Try increasing the CHUNK size. A value of 1024 or 2048 often works better.

Also, ensure no other app is using the microphone. Close video conferencing software.

Advanced: Recording with a Stream Callback

The first example used a blocking loop. For more control, use a callback function.

This is useful for real-time processing. Here is a basic callback example with PyAudio.


import pyaudio
import wave
import time

FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 5
OUTPUT_FILENAME = "output_callback.wav"

frames = []

# Define callback function
def callback(in_data, frame_count, time_info, status):
    frames.append(in_data)
    return (in_data, pyaudio.paContinue)

audio = pyaudio.PyAudio()

# Open stream using callback
stream = audio.open(format=FORMAT, channels=CHANNELS,
                    rate=RATE, input=True,
                    frames_per_buffer=CHUNK,
                    stream_callback=callback)

print("Recording with callback...")
stream.start_stream()

# Wait for the desired duration
while stream.is_active():
    time.sleep(0.1)
    if len(frames) > (RATE / CHUNK) * RECORD_SECONDS:
        stream.stop_stream()

stream.close()
audio.terminate()

# Save file
waveFile = wave.open(OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()

print(f"Audio saved to {OUTPUT_FILENAME}")

The callback function runs whenever new audio is available. It gives you more flexibility.

Conclusion

You now know how to record audio in Python. We covered two main libraries: PyAudio and SoundDevice.

Start with the simple blocking method. Move to callbacks if you need real-time features.

Remember to handle errors. Check your input device. Choose the right audio format.

Recording audio is a powerful skill. You can build voice apps, analyze sound, or create podcasts. Python makes it accessible.

Try the examples. Modify the duration and sample rate. See how it affects your recordings.