Skip to content

Instantly share code, notes, and snippets.

@cristianmiranda
Last active July 22, 2016 13:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cristianmiranda/20435d4617c1effb7df47c8e01272ad0 to your computer and use it in GitHub Desktop.
Save cristianmiranda/20435d4617c1effb7df47c8e01272ad0 to your computer and use it in GitHub Desktop.
lifx_speech.py
# NOTE: this example requires PyAudio because it uses the Microphone class
import time
import requests
import speech_recognition as sr
'''
LIFX API methods
'''
def get_light_id():
return 'd073d5123254'
def get_token():
return 'h239fhu923dnu91nf0asknldd1b43294u0wfnja120jraionlabvjqi123njisdw12'
def _do_lifx_auth_post(url, data):
try:
token = get_token()
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
}
if data:
response = requests.post(url, data=data, headers=headers)
else:
response = requests.post(url, headers=headers)
print 'Response: {0}'.format(response)
return response
except requests.HTTPError as e:
print 'Unable to submit post data {url} - {error}'.format(url=url, error=e.reason)
raise
def toggle_light(light_id):
print 'Toggle State to light {light_id}.'.format(light_id=light_id)
url = 'https://api.lifx.com/v1/lights/id:' + light_id + '/toggle'
try:
return _do_lifx_auth_post(url, {})
except:
return None
# obtain audio from the microphone
while True:
time.sleep(0.5)
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source) # listen for 1 second to calibrate the energy threshold for ambient noise levels
print("Listening...")
audio = r.listen(source)
# recognize speech using Google Speech Recognition
try:
# for testing purposes, we're just using the default API key
# to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
speech = r.recognize_google(audio, language="es-AR")
print("Google Speech Recognition thinks you said: " + speech)
if 'luz' in speech or 'luces' in speech:
toggle_light(get_light_id())
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment