PyAudio

0.2.14 · active · verified Sun Apr 12

PyAudio provides Python bindings for PortAudio, a cross-platform audio I/O library. It allows you to easily use Python to play and record audio on a variety of platforms. The current version is 0.2.14, and the library maintains a stable but slow release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize PyAudio, generate a simple sine wave, and play it back through your default audio output device. It showcases stream creation, data writing, and proper resource cleanup.

import pyaudio
import math

# Configuration
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
FREQUENCY = 440  # A4 note
DURATION = 3     # seconds

# Initialize PyAudio
p = pyaudio.PyAudio()

# Generate a sine wave
def generate_sine_wave(frequency, duration, rate, amplitude=1.0):
    samples = []
    for i in range(int(rate * duration)):
        value = amplitude * math.sin(2 * math.pi * frequency * (i / rate))
        # Scale to 16-bit integer range
        samples.append(int(value * 32767))
    # Convert to bytes (little-endian, signed)
    return b''.join(s.to_bytes(2, byteorder='little', signed=True) for s in samples)

print(f"Generating a {FREQUENCY} Hz sine wave for {DURATION} seconds...")
wave_data = generate_sine_wave(FREQUENCY, DURATION, RATE)

# Open stream for playback
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                output=True)

print("Playing audio...")
stream.write(wave_data)
print("Finished playing.")

# Clean up
stream.stop_stream()
stream.close()
p.terminate()

view raw JSON →