The issue you're encountering stems from a common misunderstanding when working with audio input streams in Python's sounddevice library (which is a wrapper around PortAudio). The main problem is that you're attempting to record from two separate microphones as if they were a single multi-channel device. However, unless both microphones are part of the same audio interface and recognized by the system as a single multi-channel device, you cannot record from them simultaneously using a single InputStream.
Here's why your current code isn't working as expected:
-
Single Input Device: By default, sounddevice.InputStream uses the system's default input device. If you have two separate microphones connected (e.g., two USB microphones), the operating system treats them as separate audio devices. The channels parameter in InputStream refers to the number of channels on a single device, not across multiple devices.
-
Channel Misinterpretation: When you set channels=[0, 1], you're actually telling the InputStream to record both channels from the default device. If your default device is a mono microphone (which most USB microphones are), it will replicate the same mono channel data into both channels, which is why you're getting the same audio recorded twice.
To fix this issue, you need to:
-
Identify Each Microphone: Determine the device IDs for each microphone connected to your system.
-
Record from Each Microphone Separately: Create separate InputStream instances for each microphone and record their audio independently.
-
Synchronize Recordings (if necessary): If synchronization between the microphones is important, additional steps are required (and perfect synchronization might not be achievable with standard hardware).
Below is the corrected code that records from two separate microphones by creating individual streams for each:
import sounddevice as sd
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
def record_audio_from_devices(duration, sample_rate, device_indices):
"""
Record audio from specified devices.
Parameters:
duration (float): Duration of recording in seconds.
sample_rate (int): Sampling rate in Hz.
device_indices (list): List of device indices to record from.
Returns:
list of np.ndarray: List of recorded audio data for each device.
"""
recordings = []
for idx, device_index in enumerate(device_indices):
print(f"Recording from device {device_index}: {sd.query_devices(device_index)['name']}")
audio_buffer = []
def callback(indata, frames, time, status):
if status:
print(status)
audio_buffer.append(indata.copy())
with sd.InputStream(samplerate=sample_rate,
channels=1,
dtype='float32',
callback=callback,
device=device_index):
sd.sleep(int(duration * 1000)) # Record for the given duration
audio_data = np.concatenate(audio_buffer, axis=0).flatten()
recordings.append(audio_data)
return recordings
# Parameters
duration = 5.0 # Record for 5 seconds
sample_rate = 44100 # Sampling rate in Hz
# List all available input devices
print("Available input devices:")
input_devices = [device for device in sd.query_devices() if device['max_input_channels'] > 0]
for idx, device in enumerate(input_devices):
print(f"{idx}: {device['name']} - Channels: {device['max_input_channels']}")
# Specify device indices for your microphones (update these based on your available devices)
device_indices = [
int(input("Enter the device index for Microphone 1: ")),
int(input("Enter the device index for Microphone 2: "))
]
# Record audio
channel_data = record_audio_from_devices(duration, sample_rate, device_indices)
# Plot and save the audio data for each device
for idx, data in enumerate(channel_data):
# Generate time axis in seconds
time_axis = np.linspace(0, duration, num=len(data))
# Plot the audio signal
plt.figure(figsize=(10, 4))
plt.plot(time_axis, data)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.title(f'Audio Signal from Microphone {device_indices[idx]}')
plt.tight_layout()
# Save the plot to a file
plot_filename = f'audio_signal_mic{device_indices[idx]}.png'
plt.savefig(plot_filename)
plt.close()
print(f'Plot saved as {plot_filename}')
# Save the audio data to a WAV file
wav_filename = f'audio_mic{device_indices[idx]}.wav'
# Normalize the audio data to the range of int16 for WAV format
max_amplitude = np.iinfo(np.int16).max
max_val = np.max(np.abs(data))
if max_val > 0:
data_int16 = np.int16(data / max_val * max_amplitude)
else:
data_int16 = np.int16(data)
wavfile.write(wav_filename, sample_rate, data_int16)
print(f'Audio saved as {wav_filename}')
Explanation of Changes:
-
Device Selection: Added code to list available input devices and select them based on their indices. This allows you to specify which microphone to record from.
-
Separate Streams: For each microphone, we create a separate InputStream using its device index. This ensures we're recording from the correct device.
-
Single Channel per Device: Since most microphones are mono, we set channels=1.
-
Recording Loop: We loop over each device and record from it individually, storing the recordings in a list.
Important Notes:
-
Synchronization Issues: Recording from multiple devices separately can lead to synchronization issues due to hardware and driver discrepancies. If precise sync is critical, consider using an audio interface that supports multiple inputs as a single device.
-
Permissions: Ensure your application has permission to access the microphones. This might require additional settings depending on your operating system.
-
Device Indices: Device indices can change between sessions or when devices are plugged/unplugged. Be sure to verify the indices each time.
-
PortAudio Limitations: The underlying PortAudio library (used by sounddevice) doesn't natively support combining multiple devices into a single stream. Workarounds involve using specific drivers or virtual audio devices.
Alternative Solution with Aggregate Devices (Advanced):
If you're on macOS or Linux, you can create an aggregate (virtual) audio device that combines multiple microphones into one multi-channel device. Here's how:
-
macOS:
- Open Audio MIDI Setup.
- Click the "+" button and select Create Aggregate Device.
- Check the boxes next to the microphones you want to include.
- This new device will now appear in your list of audio devices and can be selected in your code.
-
Linux:
- Use tools like ALSA and JACK to combine devices.
-
Windows:
- Windows doesn't natively support aggregate devices. However, you can use software like ASIO4ALL or Voicemeeter to achieve similar functionality.
After creating an aggregate device, you can modify your original code to select this device and set the channels parameter accordingly.
Updated Code for Aggregate Device:
# Assuming you've created an aggregate device named "My Aggregate Device"
aggregate_device_name = "My Aggregate Device"
def record_audio(duration, sample_rate, channels, device_name):
# Rest of your original code...
# Parameters
duration = 5.0 # Record for 5 seconds
sample_rate = 44100 # Sampling rate in Hz
channels = [0, 1] # Now valid if the aggregate device has two channels
# Find device index by name
device_list = sd.query_devices()
device_indices = [i for i, d in enumerate(device_list) if d['name'] == aggregate_device_name]
if not device_indices:
raise ValueError(f"Device '{aggregate_device_name}' not found.")
device_index = device_indices[0]
# Record audio
channel_data = record_audio(duration, sample_rate, channels, device_name=aggregate_device_name)
Final Recommendations:
-
Use a Multi-Input Audio Interface: If possible, use an external audio interface with multiple inputs. This ensures all microphones are on the same device and reduces synchronization issues.
-
Handle Exceptions: Add error handling to manage scenarios where devices are not found or streams cannot be opened.
-
Test with Short Durations: While debugging, use shorter durations to test your recordings.
-
Check Microphone Specifications: Ensure your microphones support the desired sample rates and bit depths.
By adapting your code to record from each microphone individually or by creating an aggregate device, you should be able to capture audio from both microphones as intended.