Hello!
I can help you create a Python program that performs the following tasks:
-
Record audio from two microphones: One built-in microphone (with the same origin point as the camera) and an external microphone placed 0.2 meters away from the laptop.
-
Calculate the Time Difference of Arrival (TDOA) between the two audio signals.
-
Estimate the direction from which the sound originated based on the TDOA and known microphone positions.
-
Overlay the estimated direction onto a camera image to indicate where the audio came from.
Since it doesn't have to be in real-time, we can process pre-recorded audio and image frames. Below, I'll outline the steps and provide code snippets to help you achieve this.
Note: Ensure that your environment has the necessary permissions and drivers to access the microphones and camera. Also, you'll need to install some Python libraries, which I'll mention along the way.
Step 1: Set Up the Environment
We will use the following Python libraries:
pyaudio or sounddevice for audio recording
numpy and scipy for signal processing
matplotlib for plotting (optional)
opencv-python (cv2) for image processing
Install them using pip if you haven't already:
pip install numpy scipy matplotlib opencv-python sounddevice
Step 2: Record Audio from Two Microphones
Since accessing multiple microphones can be a bit tricky, we'll use the sounddevice library, which allows us to select specific input devices.
import sounddevice as sd
import numpy as np
# List available audio input devices
print(sd.query_devices())
# Replace these indices with the indices of your microphones
mic_indices = [0, 1] # Example indices for built-in and external mics
# Recording parameters
fs = 44100 # Sampling frequency
duration = 5 # Duration of recording in seconds
def record_audio(mic_index):
sd.default.device = mic_index
print(f"Recording from microphone index {mic_index}")
recording = sd.rec(int(duration * fs), samplerate=fs, channels=1)
sd.wait()
return recording.flatten()
# Record from both microphones
audio1 = record_audio(mic_indices[0])
audio2 = record_audio(mic_indices[1])
Notes:
- Use
sd.query_devices() to find the correct indices for your microphones.
- Ensure the sampling frequency (
fs) is the same for both recordings.
- The recordings should be synchronized. However, in practice, there might be a constant offset due to hardware limitations. We'll assume they are synchronized for this example.
Step 3: Calculate the TDOA
We can calculate the TDOA by computing the cross-correlation between the two audio signals.
from scipy.signal import correlate
def calculate_tdoa(signal1, signal2, fs):
# Compute cross-correlation
correlation = correlate(signal1, signal2, mode='full')
lags = np.arange(-len(signal1) + 1, len(signal2))
# Find the lag with the maximum correlation
lag = lags[np.argmax(correlation)]
tdoa = lag / fs
return tdoa
# Calculate TDOA
tdoa = calculate_tdoa(audio1, audio2, fs)
print(f"TDOA: {tdoa} seconds")
Step 4: Estimate the Direction of Arrival
Assuming the microphones are placed along the x-axis, we can estimate the angle of arrival using the speed of sound and the TDOA.
Parameters:
d: distance between microphones (0.2 meters)
v: speed of sound in air (~343 m/s at room temperature)
import math
d = 0.2 # Distance between microphones in meters
v = 343 # Speed of sound in m/s
def estimate_angle(tdoa, d, v):
# Ensure TDOA is within the maximum possible time difference
max_tdoa = d / v
if abs(tdoa) > max_tdoa:
print("TDOA exceeds maximum possible value. Setting to maximum.")
tdoa = np.sign(tdoa) * max_tdoa
# Calculate angle of arrival
angle = math.asin((tdoa * v) / d)
angle_degrees = math.degrees(angle)
return angle_degrees
angle = estimate_angle(tdoa, d, v)
print(f"Estimated Angle of Arrival: {angle} degrees")
Notes:
- The angle calculated is relative to the normal (perpendicular) to the microphone array.
- An angle of 0 degrees means the sound arrived equally at both microphones.
- Negative angles indicate the sound came from one side, positive from the other.
Step 5: Overlay the Direction onto a Camera Image
We can use OpenCV to capture an image from the camera and overlay an arrow indicating the direction.
import cv2
def overlay_direction(image, angle_degrees):
# Get image dimensions
height, width = image.shape[:2]
# Define the center point
center = (int(width / 2), int(height / 2))
# Define the length of the arrow
arrow_length = min(width, height) // 3
# Calculate the end point of the arrow
angle_radians = math.radians(angle_degrees)
end_x = int(center[0] + arrow_length * math.sin(angle_radians))
end_y = int(center[1] - arrow_length * math.cos(angle_radians))
# Draw the arrow on the image
cv2.arrowedLine(image, center, (end_x, end_y), (0, 0, 255), 5, tipLength=0.2)
return image
# Capture an image from the camera
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
cap.release()
if ret:
# Overlay the direction
image_with_direction = overlay_direction(frame, angle)
# Display the image
cv2.imshow('Direction of Arrival', image_with_direction)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("Failed to capture image from camera.")
Notes:
- Ensure that your camera is accessible via OpenCV (usually at index
0).
- The arrow is drawn from the center of the image in the direction of the estimated angle.
- Adjust the
arrow_length and arrow properties as needed.
Bringing It All Together
Here's the complete code combining all the steps:
import sounddevice as sd
import numpy as np
from scipy.signal import correlate
import math
import cv2
# Parameters
mic_indices = [0, 1] # Replace with your microphone indices
fs = 44100 # Sampling frequency
duration = 5 # Recording duration in seconds
d = 0.2 # Distance between microphones in meters
v = 343 # Speed of sound in m/s
# Step 1: Record Audio
def record_audio(mic_index):
sd.default.device = mic_index
print(f"Recording from microphone index {mic_index}")
recording = sd.rec(int(duration * fs), samplerate=fs, channels=1)
sd.wait()
return recording.flatten()
audio1 = record_audio(mic_indices[0])
audio2 = record_audio(mic_indices[1])
# Step 2: Calculate TDOA
def calculate_tdoa(signal1, signal2, fs):
correlation = correlate(signal1, signal2, mode='full')
lags = np.arange(-len(signal1) + 1, len(signal2))
lag = lags[np.argmax(correlation)]
tdoa = lag / fs
return tdoa
tdoa = calculate_tdoa(audio1, audio2, fs)
print(f"TDOA: {tdoa} seconds")
# Step 3: Estimate Angle
def estimate_angle(tdoa, d, v):
max_tdoa = d / v
if abs(tdoa) > max_tdoa:
print("TDOA exceeds maximum possible value. Setting to maximum.")
tdoa = np.sign(tdoa) * max_tdoa
angle = math.asin((tdoa * v) / d)
angle_degrees = math.degrees(angle)
return angle_degrees
angle = estimate_angle(tdoa, d, v)
print(f"Estimated Angle of Arrival: {angle} degrees")
# Step 4: Overlay Direction on Image
def overlay_direction(image, angle_degrees):
height, width = image.shape[:2]
center = (int(width / 2), int(height / 2))
arrow_length = min(width, height) // 3
angle_radians = math.radians(angle_degrees)
end_x = int(center[0] + arrow_length * math.sin(angle_radians))
end_y = int(center[1] - arrow_length * math.cos(angle_radians))
cv2.arrowedLine(image, center, (end_x, end_y), (0, 0, 255), 5, tipLength=0.2)
return image
# Capture Image
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
cap.release()
if ret:
image_with_direction = overlay_direction(frame, angle)
cv2.imshow('Direction of Arrival', image_with_direction)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("Failed to capture image from camera.")
Additional Considerations
-
Synchronization: In practice, recording from two microphones simultaneously may not be perfectly synchronized due to hardware limitations. For more accurate results, consider using a multi-channel audio interface that guarantees synchronized recordings.
-
Noise and Reflections: The environment can affect the accuracy of TDOA estimation. Ensure that the recordings are made in a relatively quiet space without significant echo or background noise.
-
Microphone Placement: The assumption is that the microphones are placed along a straight line (the x-axis). If they are placed differently, you'll need to adjust the geometry accordingly.
-
Verification: Test the system by generating sounds from known angles and verifying if the estimated angles are accurate.
-
Error Handling: Include checks and exception handling in your code to manage potential issues, such as device availability or signal processing errors.
I hope this helps you develop your program! Let me know if you have any questions or need further assistance with any of the steps.