Sounddevice

0.5.5 · active · verified Thu Apr 09

Sounddevice is a Python library that provides a high-level API to play and record sound, built upon the PortAudio library. It allows for easy integration with NumPy for handling audio data. The current version is 0.5.5, and it maintains a relatively active release cadence with frequent patch and minor updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates playing a sine wave and then recording 2 seconds of stereo audio. It highlights the use of `numpy` for audio data generation and processing, and the `sd.play()` and `sd.rec()` functions with `sd.wait()` for blocking execution until audio operations complete.

import sounddevice as sd
import numpy as np
import time

samplerate = 44100  # samples per second
duration = 2.5      # seconds
frequency = 440     # Hz (A4 note)

# Generate a sine wave
t = np.linspace(0., duration, int(samplerate * duration), endpoint=False)
amplitude = 0.5 # To avoid clipping
data = amplitude * np.sin(2 * np.pi * frequency * t)

# Ensure data is float32, as recommended by sounddevice
data = data.astype(np.float32)

print(f"Playing a {frequency} Hz sine wave for {duration} seconds...")
sd.play(data, samplerate)
sd.wait() # Wait until playback is finished
print("Playback finished.")

# Example of recording (e.g., 2 seconds of stereo audio)
print("Recording 2 seconds of stereo audio...")
recording = sd.rec(int(2 * samplerate), samplerate=samplerate, channels=2, dtype='float32')
sd.wait() # Wait until recording is finished
print("Recording finished.")
print(f"Recorded data shape: {recording.shape}")

view raw JSON →