Certainly! Below is a Python script that captures audio input from two different microphones simultaneously, computes the Time Difference of Arrival (TDOA) between the signals, and overlays a heatmap on the computer's camera feed to indicate the direction of the sound source based on the TDOA.
Please note that capturing audio from multiple microphones simultaneously can be hardware and OS dependent. This script assumes that your system supports accessing multiple audio input devices at the same time and that you have two microphones connected.
Requirements:
- Python 3.x
numpy
scipy
sounddevice
opencv-python
matplotlib
You can install the required packages using:
pip install numpy scipy sounddevice opencv-python matplotlib
Code:
import numpy as np
import sounddevice as sd
import cv2
from scipy.signal import correlate
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
# Configuration parameters
SAMPLE_RATE = 44100 # Sampling rate in Hertz
BUFFER_DURATION = 0.1 # Duration of the audio buffer in seconds
BUFFER_SIZE = int(SAMPLE_RATE * BUFFER_DURATION)
SOUND_SPEED = 343.2 # Speed of sound in m/s
MIC_DISTANCE = 0.2 # Distance between the two mics in meters (adjust accordingly)
# Get list of input devices
devices = sd.query_devices()
input_devices = [dev for dev in devices if dev['max_input_channels'] > 0]
print("Available input devices:")
for i, dev in enumerate(input_devices):
print(f"{i}: {dev['name']}")
# Select the two microphones
mic_indices = []
for i in range(2):
device_index = int(input(f"Select microphone {i+1}: "))
mic_indices.append(input_devices[device_index]['index'])
# Function to capture audio from two microphones
def audio_callback(indata, frames, time, status):
if status:
print(status)
global audio_buffer
audio_buffer.append(indata.copy())
# Prepare buffers
audio_buffer = []
# Open audio streams for both microphones
streams = []
for mic_index in mic_indices:
stream = sd.InputStream(device=mic_index, channels=1, samplerate=SAMPLE_RATE,
blocksize=BUFFER_SIZE, callback=audio_callback)
streams.append(stream)
# Start the audio streams
for stream in streams:
stream.start()
# Initialize video capture
cap = cv2.VideoCapture(0)
# Heatmap setup
cmap = plt.get_cmap('jet')
heatmap_colors = (cmap(np.arange(cmap.N))[:, :3] * 255).astype(np.uint8)
heatmap_cmap = ListedColormap(cmap(np.linspace(0, 1, 256)))
try:
while True:
# Capture audio buffers
if len(audio_buffer) < 2:
continue
# Get and remove the oldest audio buffers
audio_data = audio_buffer.pop(0)
audio_left = audio_data[:, 0]
audio_right = audio_data[:, 1]
# Compute cross-correlation
corr = correlate(audio_left, audio_right, mode='full')
lag = np.argmax(np.abs(corr)) - (len(audio_left) - 1)
tdoa = lag / SAMPLE_RATE # Time difference in seconds
# Estimate angle of arrival
max_tdoa = MIC_DISTANCE / SOUND_SPEED
angle = np.arcsin(tdoa / max_tdoa) # Angle in radians
# Convert angle to degrees
angle_deg = np.degrees(angle)
# Read frame from camera
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break
# Generate heatmap overlay
height, width = frame.shape[:2]
heatmap = np.zeros((height, width), dtype=np.float32)
# Map angle to position on the frame
x_pos = int((angle_deg + 90) / 180 * width)
cv2.line(heatmap, (x_pos, 0), (x_pos, height), (1,), thickness=5)
# Apply colormap to heatmap
heatmap_color = cv2.applyColorMap((heatmap * 255).astype(np.uint8), cv2.COLORMAP_JET)
# Blend heatmap with the frame
overlay = cv2.addWeighted(frame, 0.7, heatmap_color, 0.3, 0)
# Display the result
cv2.imshow('Audio Heatmap Overlay', overlay)
# Break on 'q' key press
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except KeyboardInterrupt:
print('Interrupted by user')
finally:
# Stop and close audio streams
for stream in streams:
stream.stop()
stream.close()
cap.release()
cv2.destroyAllWindows()
Explanation:
-
Audio Input:
- We use
sounddevice to list available audio input devices and allow the user to select two microphones.
- We define an
audio_callback function to collect audio data into a buffer.
- We start two input streams, one for each microphone, using the selected device indices.
-
Audio Processing:
- We wait until we have enough audio data in the buffer.
- We extract audio samples from both microphones.
- We compute the cross-correlation between the two signals to estimate the TDOA.
- The lag at which the cross-correlation is maximized corresponds to the TDOA.
- We use the TDOA to estimate the angle of arrival of the sound.
-
Video Capture and Heatmap Overlay:
- We capture frames from the computer's camera using OpenCV.
- We generate a heatmap overlay by drawing a line corresponding to the estimated angle.
- We apply a colormap to the heatmap and blend it with the camera frame.
- We display the resulting frame with the overlay.
Important Notes:
-
Device Compatibility: Not all systems or sound cards support capturing from multiple audio devices simultaneously. If you encounter issues, you might need to use a multi-channel audio interface or merge the microphone inputs into one virtual device.
-
Synchronization: Ensuring that the audio streams are perfectly synchronized is critical for accurate TDOA estimation. Hardware synchronization is ideal but may not be feasible with standard consumer hardware.
-
Adjust Parameters: You might need to adjust MIC_DISTANCE to match the actual distance between your microphones and SAMPLE_RATE, BUFFER_DURATION for optimal performance.
-
Safety Checks: The script omits some error checking for brevity. In a production environment, you should add checks for buffer sizes, possible exceptions, and edge cases.
-
Permissions: Ensure that your Python environment has permission to access the microphone and camera devices.
Testing the Script:
-
Connect two microphones to your computer and note their device names from the printed list.
-
Run the script and input the indices corresponding to your microphones when prompted.
-
Make a sound (e.g., clap) from different directions relative to the microphones and observe the overlay on the video.
-
Press 'q' to exit the program.
Disclaimer:
This script is a simplified demonstration and may not work perfectly on all systems due to hardware and driver limitations. For more robust and precise applications, consider using dedicated hardware and more advanced signal processing techniques.
Feel free to ask if you have any questions or need further assistance with this script!