Skip to content

Instantly share code, notes, and snippets.

@honake
Last active April 24, 2020 22:52
Show Gist options
  • Save honake/63d3ce9b4789062412c44963f7d49df8 to your computer and use it in GitHub Desktop.
Save honake/63d3ce9b4789062412c44963f7d49df8 to your computer and use it in GitHub Desktop.
pyaudio detects great cheers and sends a signal to Arduino
import audioop
import math
import numpy as np
import pyaudio
import pyfirmata
import sys
import time
import serial
import wave
CHUNK = 2048
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=RATE,
frames_per_buffer=CHUNK,
input=True)
DURATION = 40 # 2 sec
THRESHOLD = 80 # 80 db
HALF_THRESHOLD = THRESHOLD / 2
input_levels = np.zeros(DURATION)
wf = wave.open('sound.wav', 'rb')
pin = 6
port = "/dev/{{YOUR_PORT}}"
board = pyfirmata.Arduino(port)
def detect_volume(input_levels, threshold):
if input_levels.mean() > threshold:
return True
else:
return False
while stream.is_active():
input = stream.read(CHUNK, exception_on_overflow = False)
rms = audioop.rms(input, 2) + 0.001
decibel = 20 * math.log(rms, 10)
input_levels = np.append(input_levels[1:], decibel)
print(decibel)
if detect_volume(input_levels, THRESHOLD):
board.digital[pin].write(1)
stream.stop_stream()
stream = p.open(format =
p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = wf.getframerate(),
output = True)
sound = wf.readframes(1024)
while(len(sound) > 0):
stream.write(sound)
sound = wf.readframes(1024)
stream.stop_stream()
stream.close()
p.terminate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment