Last active
August 29, 2015 13:56
-
-
Save apexskier/9299190 to your computer and use it in GitHub Desktop.
Python script to interact with Wit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pyaudio | |
from array import array | |
import wave | |
import requests | |
import json | |
CHUNK = 1024 | |
FORMAT = pyaudio.paInt16 | |
CHANNELS = 2 | |
RATE = 44100 | |
MAX_RECORD_SECONDS = 10 | |
WAVE_OUTPUT_FILENAME = "output.wav" | |
RUNNING = True | |
DEBUG = False | |
p = pyaudio.PyAudio() | |
while RUNNING: | |
stream = p.open(format=FORMAT, | |
channels=CHANNELS, | |
rate=RATE, | |
input=True, | |
frames_per_buffer=CHUNK) | |
if DEBUG: print("* listening") | |
frames = [] | |
recording = False | |
silent_time = 0 | |
for i in range(0, int(RATE / CHUNK * MAX_RECORD_SECONDS)): | |
data = stream.read(CHUNK) | |
if max((array('h', data))) > 1000: | |
if not recording: | |
if DEBUG: print("* recording") | |
else: print("****") | |
recording = True | |
silent = 0 | |
elif recording: | |
silent += 1 | |
if DEBUG: print('silent: ' + str(silent)) | |
if silent > 30: | |
if DEBUG: print("* done recording") | |
break | |
if recording: | |
if DEBUG: print(max((array('h', data)))) | |
frames.append(data) | |
if DEBUG: print("* processing") | |
else: print("----") | |
stream.stop_stream() | |
stream.close() | |
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') | |
wf.setnchannels(CHANNELS) | |
wf.setsampwidth(p.get_sample_size(FORMAT)) | |
wf.setframerate(RATE) | |
wf.writeframes(b''.join(frames)) | |
wf.close() | |
rf = open(WAVE_OUTPUT_FILENAME, 'rb') | |
d = rf.read() | |
rf.close() | |
r = requests.post('https://api.wit.ai/speech', | |
data=d, | |
headers={ | |
'content-type': 'audio/wave', | |
'authorization': 'Bearer SECRETKEY' | |
} | |
) | |
if r.status_code == 200: | |
res = r.json() | |
print("I heard: " + res['msg_body']) | |
if res['outcome']['intent'] == 'quit': | |
RUNNING = False | |
elif DEBUG: | |
print("Error: " + r.text) | |
p.terminate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment