Python:
import sounddevice as sd
import numpy as np
import threading
import time
class LoudDetector:
# Global static variable
is_loud = False
def __init__(self, threshold=0.35, cooldown=0.5):
self.threshold = threshold
self.cooldown = cooldown
self._thread = None
self._running = False
self._last_trigger = 0
def _audio_callback(self, indata, frames, time_info, status):
peak = np.max(np.abs(indata))
now = time.time()
# Update static global var
if peak > self.threshold and (now - self._last_trigger) > self.cooldown:
LoudDetector.is_loud = True
self._last_trigger = now
else:
LoudDetector.is_loud = False
def _run(self):
with sd.InputStream(callback=self._audio_callback, channels=1, samplerate=44100):
while self._running:
time.sleep(0.05) # keep thread alive without burning CPU
def start(self):
if self._running:
return
self._running = True
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
def stop(self):
if not self._running:
return
self._running = False
if self._thread is not None:
self._thread.join()
self._thread = None
def restart(self):
self.stop()
self.start()
def main():
detector = LoudDetector()
detector.start()
print("LoudDetector running in background...")
try:
while True:
if LoudDetector.is_loud:
print("LOUD DETECTED")
time.sleep(0.1)
except KeyboardInterrupt:
print("Stopping detector...")
detector.stop()
if __name__ == "__main__":
main()