-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathAudio detection. py
More file actions
39 lines (32 loc) · 1000 Bytes
/
Audio detection. py
File metadata and controls
39 lines (32 loc) · 1000 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import sounddevice as sd
import numpy as np
import librosa
import scipy.signal as signal
SAMPLE_RATE = 44100
DURATION = 2
def detect_clap(audio):
energy = np.sum(audio ** 2)
if energy > 0.25:
return True
return False
def detect_whistle(audio):
freqs, times, Sxx = signal.spectrogram(audio, SAMPLE_RATE)
whistle_band = (freqs > 1000) & (freqs < 4000)
whistle_energy = np.mean(Sxx[whistle_band, :])
if whistle_energy > 1e-6:
return True
return False
print("Listening for sounds (Clap or Whistle)... Press Ctrl+C to stop.")
try:
while True:
audio = sd.rec(int(DURATION * SAMPLE_RATE), samplerate=SAMPLE_RATE, channels=1)
sd.wait()
audio = audio.flatten()
if detect_clap(audio):
print("Clap detected!")
elif detect_whistle(audio):
print("🎵 Whistle detected!")
else:
print("No event detected.")
except KeyboardInterrupt:
print("Stopped by user.")