houndify.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import speech_recognition as sr
  2. from core import Utils
  3. from core.OrderListener import OrderListener
  4. class Houndify(OrderListener):
  5. def __init__(self, callback=None, **kwargs):
  6. """
  7. Start recording the microphone and analyse audio with Houndify api
  8. :param callback: The callback function to call to send the text
  9. :param kwargs:
  10. """
  11. OrderListener.__init__(self)
  12. # callback function to call after the translation speech/tex
  13. self.callback = callback
  14. # obtain audio from the microphone
  15. r = sr.Recognizer()
  16. with sr.Microphone() as source:
  17. # listen for 1 second to calibrate the energy threshold for ambient noise levels
  18. r.adjust_for_ambient_noise(source)
  19. Utils.print_info("Say something!")
  20. audio = r.listen(source)
  21. # recognize speech using Houndify Speech Recognition
  22. try:
  23. client_id = kwargs.get('client_id', None)
  24. key = kwargs.get('key', None)
  25. language = kwargs.get('language', "en-US")
  26. show_all = kwargs.get('show_all', False)
  27. captured_audio = r.recognize_houndify(audio, client_id=client_id, client_key=key,
  28. language=language, show_all=show_all)
  29. Utils.print_success("Houndify Speech Recognition thinks you said %s" % captured_audio)
  30. self._analyse_audio(captured_audio)
  31. except sr.UnknownValueError:
  32. Utils.print_warning("Houndify Speech Recognition could not understand audio")
  33. # callback anyway, we need to listen again for a new order
  34. self._analyse_audio(audio=None)
  35. except sr.RequestError as e:
  36. Utils.print_danger("Could not request results from Houndify Speech Recognition service; {0}".format(e))
  37. # callback anyway, we need to listen again for a new order
  38. self._analyse_audio(audio=None)
  39. def _analyse_audio(self, audio):
  40. """
  41. Confirm the audio exists annd run it in a Callback
  42. :param audio: the captured audio
  43. """
  44. # if self.main_controller is not None:
  45. # self.main_controller.analyse_order(audio)
  46. if self.callback is not None:
  47. self.callback(audio)