Skip to content

Instantly share code, notes, and snippets.

@Abathargh
Created July 18, 2020 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abathargh/3b6eb1e97b384966412b599b98c6d4d2 to your computer and use it in GitHub Desktop.
Save Abathargh/3b6eb1e97b384966412b599b98c6d4d2 to your computer and use it in GitHub Desktop.
"""
Installare le dipendenze tramite:
pip3 install requests audioop pyaudio
ed eseguire:
python3 lamp_control.py
"""
import requests
import audioop
import pyaudio
import time
from threading import Thread
lamp_state = False
first_clap = False
clap_threshold = 1500
chunk = 2048
window_size = 10
def clap(target_list, target_elem):
th_count = [element > target_elem for element in target_list].count(True)
return 1 <= th_count < 4
py = pyaudio.PyAudio()
stream = py.open(format=pyaudio.paInt16,
channels=1,
rate=48000,
input=True,
frames_per_buffer=chunk)
if __name__ == "__main__":
window = []
running = True
while running:
try:
in_data = stream.read(chunk)
rms_value = audioop.rms(in_data, 2) # paInt16 => data width = 2
window.append(rms_value)
if len(window) == window_size:
print(window, lamp_state, first_clap)
if not clap(window, clap_threshold):
first_clap = False
window.clear()
continue
if not first_clap:
first_clap = True
window.clear()
continue
lamp_state = not lamp_state
print("closing" if not lamp_state else "opening")
Thread(target=requests.post, args=("http://localhost/status", {"open": lamp_state})).start()
first_clap = False
window.clear()
except KeyboardInterrupt:
running = False
stream.stop_stream()
stream.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment