Of course. The term "deep sounder" most commonly refers to a type of sonar (SOund Navigation And Ranging) used to measure depth, often in water. We can simulate this principle using your computer's microphone and speakers.
The code will perform the following steps:
- Generate a "Ping": Create a short, specific sound pulse (like a high-frequency chirp).
- Play the Ping: Send the sound out through your speakers.
- Record Audio: Simultaneously, record with your microphone. The recording will capture both the sound coming directly from your speakers and the "echo" of that sound bouncing off a nearby object (like a wall).
- Analyze the Recording: Use signal processing (specifically, cross-correlation) to find the time delay between the original ping and its echo.
- Calculate Distance: Use the time delay and the speed of sound to calculate the distance to the object.
This is a simulation and its accuracy will be highly dependent on your microphone/speaker quality, background noise, and the acoustics of your room. But it's an excellent demonstration of the core principles.
Prerequisites
You'll need to install a few Python libraries. PyAudio can be tricky, so follow instructions carefully.
-
Install Libraries:
pip install numpy pyaudio scipy
- Note for PyAudio: On macOS, you might need
brew install portaudio. On Windows, pip often works directly. On Linux, you might need sudo apt-get install portaudio19-dev python3-pyaudio.
-
Hardware Setup: For this to work best, your microphone and speakers should be on the same device (e.g., a laptop).
The Python Audio Code for a "Deep Sounder"
This code defines functions to generate a sound, play and record simultaneously, and then analyze the result to find the distance to the nearest large object (like a wall).
import pyaudio
import numpy as np
import time
from scipy.signal import chirp, find_peaks, correlate
# --- Configuration Constants ---
# Audio settings
RATE = 44100 # Samples per second
CHANNELS = 1 # Mono audio
FORMAT = pyaudio.paInt16 # 16-bit audio format
CHUNK_SIZE = 1024 # Samples per buffer
# Ping signal settings
PING_START_FREQ = 2000 # Starting frequency of the chirp (in Hz)
PING_END_FREQ = 10000 # Ending frequency of the chirp (in Hz)
PING_DURATION = 0.05 # Duration of the ping signal (in seconds)
# Recording and Analysis settings
RECORD_SECONDS = 0.5 # How long to listen for an echo
SPEED_OF_SOUND = 343 # Speed of sound in meters/second (at ~20°C)
MIN_DISTANCE_M = 0.3 # Minimum distance to report (ignores direct speaker-to-mic sound)
def generate_ping_signal():
"""Generates a frequency-swept 'chirp' signal for the ping."""
print(f"Generating a {PING_DURATION*1000:.0f} ms chirp from {PING_START_FREQ/1000}kHz to {PING_END_FREQ/1000}kHz...")
t = np.linspace(0, PING_DURATION, int(PING_DURATION * RATE), endpoint=False)
# Using a logarithmic chirp can sometimes improve performance
ping = chirp(t, f0=PING_START_FREQ, f1=PING_END_FREQ, t1=PING_DURATION, method='linear')
# Normalize to 16-bit integer range
ping = (ping * 32767).astype(np.int16)
return ping
def find_echo(recording, original_ping):
"""
Analyzes the recording to find the time delay of the echo using cross-correlation.
"""
# Normalize both signals to have zero mean and unit variance
recording_norm = (recording - np.mean(recording)) / np.std(recording)
ping_norm = (original_ping - np.mean(original_ping)) / np.std(original_ping)
# Perform cross-correlation
correlation = correlate(recording_norm, ping_norm, mode='valid')
# The first peak will be the direct sound from speaker to mic. We need the second one.
# We define a minimum sample delay based on our minimum distance.
min_sample_delay = int(MIN_DISTANCE_M * 2 / SPEED_OF_SOUND * RATE)
# Find all peaks in the correlation
peaks, _ = find_peaks(correlation, height=np.max(correlation)*0.1, distance=min_sample_delay)
if len(peaks) > 1:
# The first significant peak is the original sound. The second is the echo.
# We assume the highest peak is the direct sound.
direct_sound_index = peaks[np.argmax(correlation[peaks])]
# Find the next significant peak after the direct sound
echo_index = -1
for peak_idx in sorted(peaks):
# Check if this peak is significantly after the direct sound
if peak_idx > direct_sound_index + min_sample_delay:
echo_index = peak_idx
break
if echo_index != -1:
time_delay = (echo_index - direct_sound_index) / RATE
distance = (time_delay * SPEED_OF_SOUND) / 2 # Divide by 2 for round trip
return distance
return None # No distinct echo found
def main():
"""Main function to run the deep sounder."""
p = pyaudio.PyAudio()
ping_signal = generate_ping_signal()
print("\nOpening audio stream...")
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK_SIZE)
print("--- Place your device facing a wall or large object. ---")
print("--- Press ENTER to send a ping. ---")
input() # Wait for user to press Enter
print("Sending ping and listening for echo...")
# Play the ping
stream.write(ping_signal.tobytes())
# Record the audio right after
frames = []
num_chunks_to_record = int((RATE / CHUNK_SIZE) * RECORD_SECONDS)
for _ in range(num_chunks_to_record):
data = stream.read(CHUNK_SIZE)
frames.append(data)
print("Recording finished. Analyzing...")
# Stop and close the stream
stream.stop_stream()
stream.close()
p.terminate()
# Convert recorded frames to a numpy array
recorded_audio = np.frombuffer(b''.join(frames), dtype=np.int16)
# Find the echo and calculate distance
distance = find_echo(recorded_audio, ping_signal)
if distance is not None:
print("\n=====================================")
print(f" ECHO DETECTED!")
print(f" Distance: {distance:.2f} meters")
print("=====================================")
else:
print("\n-------------------------------------")
print(" No distinct echo was found.")
print(" Try a quieter room, a larger object,")
print(" or adjust the PING/RECORD settings.")
print("-------------------------------------")
if __name__ == '__main__':
main()
How to Run and Interpret the Results
- Save the code: Save the code above as a Python file (e.g.,
sonar.py).
- Set up your environment:
- Sit in a relatively quiet room.
- Place your laptop or device so it's facing a large, flat surface like a wall, a few feet away.
- Make sure nothing is blocking the speakers or microphone.
- Run from the terminal:
python sonar.py
- Follow the prompts: The script will ask you to press Enter. When you do, it will play a short, high-pitched chirp and immediately start recording.
- Check the output: After a moment, it will print either the calculated distance to the object or a message that no echo was found.
Alternative: Simple "Deep Sound" Generator
If by "deep sounder" you simply meant code to generate a very low-frequency (deep) sound, the code is much simpler. This will just play a low bass tone.
import pyaudio
import numpy as np
# --- Configuration ---
RATE = 44100 # Samples per second
FREQUENCY = 80 # Frequency in Hz (e.g., 80 Hz is a deep bass note)
DURATION = 5 # Duration in seconds
VOLUME = 0.5 # Volume from 0.0 to 1.0
def play_tone():
"""Generates and plays a continuous low-frequency tone."""
p = pyaudio.PyAudio()
# Generate the sound wave
t = np.linspace(0, DURATION, int(RATE * DURATION), False)
tone = np.sin(FREQUENCY * t * 2 * np.pi)
# Convert to 16-bit audio format
audio_data = (tone * VOLUME * 32767).astype(np.int16).tobytes()
# Open stream and play
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=RATE,
output=True)
print(f"Playing a {FREQUENCY} Hz tone for {DURATION} seconds...")
stream.write(audio_data)
print("Playback finished.")
# Clean up
stream.stop_stream()
stream.close()
p.terminate()
if __name__ == '__main__':
play_tone()