Skip to content

Instantly share code, notes, and snippets.

@smathot
Created November 23, 2015 09:36
Show Gist options
  • Save smathot/46be0435d43452b34159 to your computer and use it in GitHub Desktop.
Save smathot/46be0435d43452b34159 to your computer and use it in GitHub Desktop.
OpenSesame voicekey
import pyaudio
import wave
import sys
import struct
import math
TAP_THRESHOLD = 0.050
FORMAT = pyaudio.paInt16
SHORT_NORMALIZE = (1.0/32768.0)
CHANNELS = 2
RATE = 44100
INPUT_BLOCK_TIME = 0.01
INPUT_FRAMES_PER_BLOCK = int(RATE*INPUT_BLOCK_TIME)
chunk=1024
def get_rms(block):
"""Get root mean square as a measure of loudness"""
count = len(block)/2
format = "%dh" % (count)
shorts = struct.unpack( format, block )
sum_squares = 0.0
for sample in shorts:
n = sample * SHORT_NORMALIZE
sum_squares += n*n
return math.sqrt( sum_squares / count )
# Open the mic
stream = pyaudio.PyAudio().open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
input_device_index=0,
frames_per_buffer=INPUT_FRAMES_PER_BLOCK
)
# Listen until a sound has been detected
start_response_interval = self.time()
end_response_interval = None
trial_duration = 4000
while self.time() - start_response_interval < trial_duration:
try:
block = stream.read(chunk)
all.append(block)
except IOError as e:
print e
loudness = get_rms( block )
if loudness > TAP_THRESHOLD:
end_response_interval = self.time()
response_loudness = loudness
if end_response_interval is None:
set_response(response='timeout', response_time=None)
var.loudness = "timeout"
else:
rt = end_response_interval - start_response_interval
set_response(response='detected', response_time=rt)
var.loudness = response_loudness
stream.close()
pyaudio.PyAudio().terminate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment