Skip to main content

SoundDevice Examples

SoundDevice Library How To Examples in Python

The SoundDevice library is a Python wrapper for the PortAudio library, which provides cross-platform audio input and output. This library allows you to easily record and play audio in your Python programs. In this tutorial, we will cover 10 examples of how to use the SoundDevice library in Python.

Example 1: Playing a Sine Wave

import sounddevice as sd
import numpy as np

# Generate a sine wave
duration = 3 # seconds
frequency = 440 # Hz (A4)
sampling_rate = 44100 # samples per second
t = np.linspace(0, duration, int(duration * sampling_rate), endpoint=False)
data = 0.3 * np.sin(2 * np.pi * frequency * t)

# Play the sine wave
sd.play(data, sampling_rate)
sd.wait() # Wait until the sound is finished playing

Expected Output: You should hear a 440 Hz sine wave playing for 3 seconds.

Example 2: Recording Audio

import sounddevice as sd

# Set the sampling rate and duration of the recording
sampling_rate = 44100 # samples per second
duration = 5 # seconds

# Record audio
recording = sd.rec(int(duration * sampling_rate), samplerate=sampling_rate, channels=1)
sd.wait() # Wait until the recording is finished

# Save the recording to a WAV file
sd.write('output.wav', recording, samplerate=sampling_rate)

Expected Output: This example will record audio for 5 seconds and save it to a WAV file called "output.wav".

Example 3: Playing and Recording Simultaneously

import sounddevice as sd

# Set the sampling rate and duration of the recording
sampling_rate = 44100 # samples per second
duration = 5 # seconds

# Record and play audio simultaneously
recording = sd.playrec(np.zeros(int(duration * sampling_rate)), samplerate=sampling_rate, channels=1)
sd.wait() # Wait until the recording and playback are finished

# Save the recording to a WAV file
sd.write('output.wav', recording, samplerate=sampling_rate)

Expected Output: This example will record audio for 5 seconds while simultaneously playing back silence. The recording will be saved to a WAV file called "output.wav".

Example 4: Changing the Default Input Device

import sounddevice as sd

# Get a list of available input devices
input_devices = sd.query_devices(kind='input')
print("Available input devices:")
for i, device in enumerate(input_devices):
print(f"{i}: {device['name']}")

# Change the default input device
desired_device = input("Enter the number of the desired input device: ")
sd.default.device[0] = int(desired_device)

Expected Output: This example will display a list of available input devices and prompt the user to enter the number of the desired input device. The default input device will then be changed to the selected device.

Example 5: Changing the Default Output Device

import sounddevice as sd

# Get a list of available output devices
output_devices = sd.query_devices(kind='output')
print("Available output devices:")
for i, device in enumerate(output_devices):
print(f"{i}: {device['name']}")

# Change the default output device
desired_device = input("Enter the number of the desired output device: ")
sd.default.device[1] = int(desired_device)

Expected Output: This example will display a list of available output devices and prompt the user to enter the number of the desired output device. The default output device will then be changed to the selected device.

Example 6: Adjusting the Volume

import sounddevice as sd

# Set the volume to 50% (0.5)
volume = 0.5
sd.default.volume = volume

# Play a sound to test the volume
sd.play([1, 1, 1], samplerate=44100)
sd.wait()

Expected Output: This example will set the default volume to 50% and play a sound to test the volume. The sound should be played at half the normal volume.

Example 7: Streaming Audio from a Microphone

import sounddevice as sd

# Set the sampling rate and duration of the stream
sampling_rate = 44100 # samples per second
duration = 10 # seconds

# Start streaming audio from the default input device
stream = sd.InputStream(samplerate=sampling_rate, channels=1)
stream.start()

# Read and process the audio data in chunks
for i in range(int(duration * sampling_rate)):
data, _ = stream.read(1)
# Process the audio data here

# Stop the audio stream
stream.stop()

Expected Output: This example will stream audio from the default input device for 10 seconds. You can add code to process the audio data within the loop.

Example 8: Visualizing Audio with Matplotlib

import sounddevice as sd
import matplotlib.pyplot as plt

# Set the sampling rate and duration of the recording
sampling_rate = 44100 # samples per second
duration = 5 # seconds

# Record audio
recording = sd.rec(int(duration * sampling_rate), samplerate=sampling_rate, channels=1)
sd.wait() # Wait until the recording is finished

# Plot the recorded audio
plt.plot(recording)
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.show()

Expected Output: This example will record audio for 5 seconds and plot the recorded audio using Matplotlib. The x-axis represents time, and the y-axis represents the amplitude of the audio signal.

Example 9: Changing the Buffer Size

import sounddevice as sd

# Set the desired buffer size
buffer_size = 1024

# Change the default buffer size
sd.default.buffer_size = buffer_size

# Print the actual buffer size
print(f"Actual buffer size: {sd.default.buffer_size}")

Expected Output: This example will change the default buffer size to 1024 and print the actual buffer size used by the system.

Example 10: Using Callbacks

import sounddevice as sd

# Define a callback function to process audio data
def callback(indata, outdata, frames, time, status):
# Process the audio data here

# Start streaming audio with the callback function
stream = sd.Stream(callback=callback)
stream.start()

# Keep the program running until user interrupts
input("Press enter to quit...")
stream.stop()

Expected Output: This example demonstrates how to use callbacks with the SoundDevice library. The callback function will be called whenever new audio data is available. You can add code to process the audio data within the callback function. The program will continue running until the user presses enter.

These examples cover a range of common use cases for the SoundDevice library in Python. Whether you need to play audio, record audio, change device settings, or process audio data, the SoundDevice library provides a convenient and easy-to-use solution.