Created
December 18, 2015 11:08
-
-
Save abhishekmurthy/92b0b1e7a6236909311d to your computer and use it in GitHub Desktop.
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 | |
import wave | |
import subprocess, shlex | |
import os | |
import json | |
import re | |
import urllib | |
CHUNK = 1024 | |
FORMAT = pyaudio.paInt16 | |
CHANNELS = 2 | |
RATE = 44100 | |
RECORD_SECONDS = 5 | |
WAVE_OUTPUT_FILENAME = "record.wav" | |
p = pyaudio.PyAudio() | |
inputKey = '' | |
while inputKey != 'q': | |
frames = [] | |
stream = p.open(format=FORMAT, | |
channels=CHANNELS, | |
rate=RATE, | |
input=True, | |
frames_per_buffer=CHUNK) | |
print("* recording") | |
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): | |
data = stream.read(CHUNK) | |
frames.append(data) | |
print("* done recording") | |
stream.stop_stream() | |
stream.close() | |
# p.terminate() | |
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() | |
# sox command | |
commandLine = 'sox record.wav record.flac' | |
args = shlex.split(commandLine) | |
proc = subprocess.call(args) | |
# google wget... | |
#commandLine = 'wget --post-file record.flac --header="Content-Type: audio/x-flac; rate=44100" -O - "http://www.google.com/speech-api/v2/recognize?lang=en-us&client=chromium"' | |
commandLine = 'wget --post-file record.flac --header="Content-Type: audio/x-flac; rate=44100" -O - "http://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key=AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw"' | |
args = shlex.split(commandLine) | |
#proc = subprocess.call(args, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) | |
proc = subprocess.Popen(args, stdout=subprocess.PIPE) | |
data = proc.communicate() | |
r_json = json.loads(data[0].split('\n')[1]) | |
print r_json['result'][0]['alternative'][0]['transcript'] | |
r_json = r_json['result'][0]['alternative'][0]['transcript'] | |
response = urllib.urlopen("http://suggestqueries.google.com/complete/search?client=firefox&q=" + r_json).read() | |
print re.findall(r'"([^"]*)"', response)[1] | |
#print 'want to record next sentence? press q to exit any other key to continue...', | |
inputKey = raw_input() | |
os.remove("record.wav") | |
os.remove("record.flac") | |
p.terminate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment