import sounddevice as sd import numpy as np import matplotlib.pyplot as plt # Parameters for gunshot detection threshold = 0.2 # Amplitude threshold for gunshot detection def list_input_devices(): devices = sd.query_devices() print("Available input devices:") for i, device in enumerate(devices): if 'max_input_channels' in device: print(f"{i}: {device['name']}") def plot_sound_origin(audio_data, is_gunshot): # Calculate the average intensity for the left and right channels left_intensity = np.mean(audio_data[:, 0]) right_intensity = np.mean(audio_data[:, 1]) # Determine the sound origin based on intensity total_intensity = left_intensity + right_intensity if total_intensity == 0: # Avoid division by zero left_position = right_position = 0.5 else: left_position = left_intensity / total_intensity right_position = right_intensity / total_intensity # Plot the sound intensity plt.clf() plt.plot([0, 1], [0, 0], 'k-') # Horizontal line plt.plot([left_position], [0], 'bo', markersize=10, label='Sound Origin') # Plot gunshot marker if detected if is_gunshot: plt.plot([left_position], [0], 'rx', markersize=12, label='Gunshot Detected') plt.xlim(-0.1, 1.1) plt.ylim(-1, 1) plt.xlabel('Sound Origin (Left to Right)') plt.title('Sound Origin Determination') plt.legend() plt.pause(0.1) # Pause to allow the plot to update def audio_callback(indata, frames, time, status): if status: print("Error:", status) # Check if any element exceeds the threshold (potential gunshot) is_gunshot = np.max(np.abs(indata)) > threshold plot_sound_origin(indata, is_gunshot) # List available input devices and prompt the user to choose one list_input_devices() device_idx = int(input("Enter the index of the input device to use: ")) # Get the chosen input device info devices = sd.query_devices() device_info = devices[device_idx] # Parameters for audio recording duration = None # None for continuous listening fs = int(device_info['default_samplerate']) buffer_size = 1024 # Start listening to audio from the selected input device print(f"Listening to audio from input device {device_idx}: {device_info['name']}...") with sd.InputStream(callback=audio_callback, device=device_idx, channels=2, samplerate=fs, blocksize=buffer_size): input("Press Enter to stop...") # Wait for user input to stop