Google.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import speech_recognition as sr
  2. from core.OrderListener import OrderListener
  3. class Google(OrderListener):
  4. def __init__(self, callback=None, **kwargs):
  5. """
  6. Start recording the microphone and analyse audio with google api
  7. :param callback: The callback function to call to send the text
  8. :param kwargs:
  9. """
  10. OrderListener.__init__(self)
  11. """
  12. Start recording the microphone
  13. :return:
  14. """
  15. # callback function to call after the translation speech/tex
  16. self.callback = callback
  17. # obtain audio from the microphone
  18. r = sr.Recognizer()
  19. with sr.Microphone() as source:
  20. # listen for 1 second to calibrate the energy threshold for ambient noise levels
  21. r.adjust_for_ambient_noise(source)
  22. print("Say something!")
  23. audio = r.listen(source)
  24. # recognize speech using Google Speech Recognition
  25. try:
  26. # for testing purposes, we're just using the default API key
  27. # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
  28. # instead of `r.recognize_google(audio)`
  29. key = kwargs.get('key', None)
  30. language = kwargs.get('language', "en-US")
  31. show_all = kwargs.get('show_all', False)
  32. captured_audio = r.recognize_google(audio, key=key, language=language, show_all=show_all)
  33. print "Google Speech Recognition thinks you said %s" % captured_audio
  34. self._analyse_audio(captured_audio)
  35. except sr.UnknownValueError:
  36. print("Google Speech Recognition could not understand audio")
  37. except sr.RequestError as e:
  38. print("Could not request results from Google Speech Recognition service; {0}".format(e))
  39. def _analyse_audio(self, audio):
  40. # if self.main_controller is not None:
  41. # self.main_controller.analyse_order(audio)
  42. if self.callback is not None:
  43. self.callback(audio)