-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmic_led.py
More file actions
61 lines (52 loc) · 1.56 KB
/
Copy pathmic_led.py
File metadata and controls
61 lines (52 loc) · 1.56 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from gpiozero import LED
import pyaudio
import numpy as np
import time
# Define GPIO pins
ledPin = 17
# Initialize LED
led = LED(ledPin)
# Setup PyAudio
CHUNK = 1024 # Number of audio samples per buffer
RATE = 44100 # Sampling rate
p = pyaudio.PyAudio()
# Open audio stream
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
def detect_sound(threshold=1000):
data = np.frombuffer(stream.read(CHUNK), dtype=np.int16)
peak = np.average(np.abs(data))
print(f"Detected peak: {peak}", flush=True)
return peak > threshold
def loop():
print("Entering main loop...", flush=True)
while True:
print("Listening for sound...", flush=True)
if detect_sound():
print("Sound detected!", flush=True)
led.on()
print("LED turned ON", flush=True)
else:
print("No sound detected", flush=True)
led.off()
print("LED turned OFF", flush=True)
time.sleep(0.1)
print("Loop iteration completed", flush=True)
def destroy():
print("Cleaning up resources...", flush=True)
led.close()
stream.stop_stream()
stream.close()
p.terminate()
print("Resources cleaned up", flush=True)
if __name__ == '__main__':
print("Program is starting...", flush=True)
try:
loop()
except KeyboardInterrupt:
print("KeyboardInterrupt detected, ending program...", flush=True)
destroy()
print("Program terminated", flush=True)