PyAudio Tutorial: The Ultimate Python Audio Library Guide

July 5, 2026 14 min read Python, Audio, PyAudio

Master PyAudio — the cross-platform Python library for recording, playing, and processing audio. This comprehensive guide covers everything from installation and first steps to advanced real-time streams, AI voice assistants, and performance tuning.

Table of Contents

1. Introduction

PyAudio is the most popular Python library for cross-platform audio input and output. It gives you low-level control over your sound hardware, making it essential for voice assistants, music applications, telephony, and real-time audio processing. Whether you're a beginner building your first voice recorder or an expert developing a low-latency audio engine, PyAudio has you covered.

Key Takeaway: PyAudio is a Python wrapper for PortAudio — a battle-tested C library that powers audio applications on Windows, macOS, and Linux.

2. What is PyAudio?

PyAudio provides Python bindings for PortAudio, the cross-platform audio I/O library. It allows you to:

It's the foundation for many Python audio tools, including speech recognition, music generation, and acoustic analysis.

3. Features of PyAudio

FeatureDescription
Cross‑platformWindows, macOS, Linux
Low‑latency streamingCallback and blocking I/O
Device enumerationList all input/output devices
Multiple formatspaInt16, paFloat32, paInt24, etc.
Multi‑channelMono, stereo, surround
Full‑duplexRecord and play simultaneously

4. Why Use PyAudio?

Pro Tip: PyAudio is the recommended choice for applications that require low-latency audio I/O, such as guitar effects pedals, VoIP clients, and AI voice assistants.

5. Installation

5.1 pip install pyaudio

bashpip install pyaudio

5.2 Windows

bashpip install pyaudio

If you encounter errors, try installing from a pre‑built wheel or use conda install pyaudio.

5.3 Linux (Ubuntu/Debian)

bashsudo apt-get install portaudio19-dev python3-pyaudio

5.4 macOS

bashbrew install portaudio
pip install pyaudio
Warning: On Apple Silicon (M1/M2), set environment variables before installing:
CFLAGS="-I/opt/homebrew/include" LDFLAGS="-L/opt/homebrew/lib" pip install pyaudio

6. System Requirements

7. Dependencies

8. Verify Installation

Run the following script to check your PyAudio setup:

Python import pyaudio
p = pyaudio.PyAudio()
print("PyAudio version:", pyaudio.__version__)
print("Device count:", p.get_device_count())
for i in range(p.get_device_count()):
    info = p.get_device_info_by_index(i)
    print(f"{i}: {info['name']}")
p.terminate()

Expected output: A list of audio devices, including your microphone and speakers.

9. First PyAudio Program

This example records 3 seconds of audio and plays it back immediately.

Python import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 3

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE,
    input=True, frames_per_buffer=CHUNK)

print("Recording...")
frames = []
for _ in range(int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("Playing back...")
stream.stop_stream(); stream.close()

play_stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, output=True)
play_stream.write(b''.join(frames))
play_stream.stop_stream(); play_stream.close()
p.terminate()
Tip: Always close streams and terminate PyAudio to release system resources.

10. Recording Audio

Use stream.read() to capture audio data. The example below saves the recording to a WAV file.

Python import pyaudio, wave

p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100,
    input=True, frames_per_buffer=1024)

frames = []
for _ in range(0, int(44100 / 1024 * 5)):
    frames.append(stream.read(1024))

stream.stop_stream(); stream.close(); p.terminate()

wf = wave.open("recording.wav", 'wb')
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
wf.setframerate(44100)
wf.writeframes(b''.join(frames))
wf.close()

Common mistake: Forgetting to set the correct sample width. Use p.get_sample_size(FORMAT).

11. Playing Audio

To play a WAV file, read it with the wave module and write chunks to the output stream.

Python import pyaudio, wave

wf = wave.open("recording.wav", 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
    channels=wf.getnchannels(), rate=wf.getframerate(), output=True)

data = wf.readframes(1024)
while data:
    stream.write(data)
    data = wf.readframes(1024)

stream.close(); p.terminate(); wf.close()

12. Working with WAV Files

WAV is the most common format for PyAudio. Use the built‑in wave module to read and write WAV files. For advanced features like metadata extraction or format conversion, use scipy.io.wavfile or soundfile.

13. Microphone Input

To select a specific microphone, use input_device_index. List all devices with get_device_info_by_index().

Python import pyaudio
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
    info = p.get_device_info_by_index(i)
    if info['maxInputChannels'] > 0:
        print(f"Input device {i}: {info['name']}")

14. Speaker Output

Use output_device_index to choose a speaker. Most systems use the default output device.

15. Real‑time Audio Processing

PyAudio supports a callback mode for non‑blocking, low‑latency processing. The callback function is called whenever new audio data is available.

Python import pyaudio, numpy as np

def callback(in_data, frame_count, time_info, status):
    audio = np.frombuffer(in_data, dtype=np.int16)
    processed = (audio * 0.5).astype(np.int16) # volume reduction
    return (processed.tobytes(), pyaudio.paContinue)

p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100,
    input=True, output=True, stream_callback=callback)
stream.start_stream()
while stream.is_active():
    pass
stream.close(); p.terminate()
Pro Tip: Use NumPy for efficient audio processing inside the callback.

16. Stream Handling

Always manage streams properly: open(), start_stream(), stop_stream(), and close(). Use try/finally blocks to ensure cleanup.

17. Audio Parameters

Key parameters when opening a stream:

18. Buffer Size Explained

Buffer size (frames_per_buffer) determines the latency and CPU usage. Smaller buffers = lower latency but higher risk of underruns. A typical value is 1024 or 512.

19. Sample Rate Explained

Sample rate is the number of samples per second. Common rates: 8000 Hz (telephony), 44100 Hz (CD quality), 48000 Hz (video), 96000 Hz (high resolution).

20. Channels Explained

Channels refer to the number of audio tracks. Mono = 1 channel, Stereo = 2 channels, Surround = 6 or more.

21. Audio Formats Explained

FormatDescription
paInt1616‑bit signed integer (most common)
paInt2424‑bit signed integer
paFloat3232‑bit floating point (good for DSP)
paInt88‑bit signed integer

22. Practical Examples

23. AI Voice Assistant Example

Combine PyAudio with speech_recognition and pyttsx3 to create a simple voice assistant.

Python import speech_recognition as sr
import pyttsx3

recognizer = sr.Recognizer()
engine = pyttsx3.init()

with sr.Microphone() as source:
    print("Listening...")
    audio = recognizer.listen(source)
    try:
        text = recognizer.recognize_google(audio)
        print(f"You said: {text}")
        engine.say("You said " + text)
        engine.runAndWait()
    except sr.UnknownValueError:
        print("Could not understand")

24. Voice Recorder Project

Build a full-featured voice recorder with start/stop, pause, and save options using PyAudio and Tkinter.

25. Live Audio Monitor

Display real-time waveform or volume levels using Matplotlib. Use the callback to update the plot.

26. Common Errors & Troubleshooting

27. Performance Tips

28. Best Practices

29. Security Considerations

30. Advantages & Limitations

Advantages:

Limitations:

31. PyAudio vs Alternatives

LibraryProsCons
PyAudioLow-level control, cross-platform, matureComplex API
sounddeviceNumPy-friendly, simpler APILess control over buffers
pygame.mixerEasy playback for gamesLimited recording, less flexible
playsoundOne‑line playbackNo recording, no streaming

32. Frequently Asked Questions (20+)

What is PyAudio used for?

PyAudio is used for cross-platform audio input/output, including recording, playback, and real‑time processing.

Is PyAudio free?

Yes, PyAudio is open-source under the MIT license.

How do I install PyAudio?

pip install pyaudio (see installation section for platform-specific steps).

Can PyAudio record and play simultaneously?

Yes, using full‑duplex streams with the callback API.

What is the difference between PyAudio and sounddevice?

PyAudio is lower‑level; sounddevice offers a higher‑level, NumPy‑centric API.

How do I select a microphone?

Use input_device_index parameter after enumerating devices.

What sample rate should I use?

44100 Hz for general use, 16000 Hz for speech recognition.

What is buffer size?

It's the number of frames per chunk; smaller values reduce latency.

Does PyAudio support MP3?

No, only PCM formats. Use additional libraries like pydub for MP3.

How do I fix 'Device unavailable' error?

Check that your microphone is not in use by another application.

Can I use PyAudio with asyncio?

Yes, by using threads or the callback API.

What is the maximum sample rate?

Depends on your hardware, but typically 192 kHz.

How do I apply effects to audio?

Process the audio data inside the callback or after recording.

Is PyAudio safe for production?

Yes, it's used in many production applications.

Can I record system audio?

Not directly; you need a loopback driver or virtual audio cable.

How do I get device info?

Use get_device_info_by_index().

What are common errors?

Device unavailable, buffer underflow, format mismatch.

How do I reduce latency?

Use smaller buffer sizes and the callback API.

Can I process audio in real-time?

Yes, the callback API is designed for real‑time processing.

Where can I find more examples?

Check the official PyAudio documentation and GitHub repository.

33. Conclusion

PyAudio is the Swiss Army knife for audio in Python. From simple voice recorders to professional DAWs and AI voice assistants, it provides the foundation for any audio project. With the knowledge from this tutorial, you're ready to build robust, cross-platform audio applications.

Key Takeaways:

📝 Quiz: Test Your PyAudio Knowledge

1. Which method is used to read audio data from a stream?
A) stream.write()   B) stream.read()   C) stream.input()   D) stream.record()
2. What is the most common audio format used with PyAudio?
A) paFloat32   B) paInt16   C) paInt24   D) paInt8
3. How do you get the number of audio devices?
A) p.get_device_count()   B) p.device_count()   C) len(p.devices)   D) p.num_devices()
4. Which API is best for low‑latency processing?
A) Blocking I/O   B) Callback   C) Threaded   D) Async
5. How do you terminate PyAudio?
A) p.close()   B) p.terminate()   C) p.finish()   D) p.stop()
6. Which library is PyAudio built on?
A) ALSA   B) PortAudio   C) PulseAudio   D) CoreAudio
7. How do you specify a microphone?
A) input_device_index   B) mic_id   C) device_id   D) input_index
8. What does CHUNK represent?
A) Number of channels   B) Buffer size   C) Sample rate   D) Format
9. Can PyAudio record and play at the same time?
A) Yes   B) No   C) Only on Linux   D) Only with external library
10. Which format is best for DSP?
A) paInt16   B) paInt24   C) paFloat32   D) paInt8

🧪 Practice Exercises

  1. Write a program that records audio and saves it as a WAV file.
  2. Create a simple audio player that can pause and resume playback.
  3. Implement a live echo effect using the callback API.
  4. Build a voice‑activated recorder that starts recording when sound exceeds a threshold.
  5. Combine PyAudio with matplotlib to display a real‑time waveform.

📦 Mini Project: Audio Recorder with GUI

Build a Tkinter app with buttons for Start Recording, Stop, and Playback. Use PyAudio for recording and playback, and save the final recording as a WAV file.


🏆 Final Project: Real‑time Voice Changer

Create a real‑time voice changer that applies pitch shifting and reverb effects to microphone input. Use PyAudio's callback API and NumPy for DSP. Add a GUI to control effect parameters.


📌 Summary & Key Takeaways


💼 Interview Questions

  1. Explain the difference between blocking and callback I/O in PyAudio.
  2. How would you reduce audio latency in a PyAudio application?
  3. What are the common audio formats used in PyAudio?
  4. How do you handle device selection in PyAudio?
  5. Describe how to apply real‑time effects using the callback API.

2026 LegalCodx — Comprehensive PyAudio Tutorial