bing.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import speech_recognition as sr
  2. from core import Utils
  3. from core.OrderListener import OrderListener
  4. class Bing(OrderListener):
  5. def __init__(self, callback=None, **kwargs):
  6. """
  7. Start recording the microphone and analyse audio with Bing 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 Bing Speech Recognition
  22. try:
  23. key = kwargs.get('key', None)
  24. language = kwargs.get('language', "en-US")
  25. show_all = kwargs.get('show_all', False)
  26. captured_audio = r.recognize_bing(audio, key=key, language=language, show_all=show_all)
  27. Utils.print_success("Bing Speech Recognition thinks you said %s" % captured_audio)
  28. self._analyse_audio(captured_audio)
  29. except sr.UnknownValueError:
  30. Utils.print_warning("Bing Speech Recognition could not understand audio")
  31. # callback anyway, we need to listen again for a new order
  32. self._analyse_audio(audio=None)
  33. except sr.RequestError as e:
  34. Utils.print_danger("Could not request results from Bing Speech Recognition service; {0}".format(e))
  35. # callback anyway, we need to listen again for a new order
  36. self._analyse_audio(audio=None)
  37. def _analyse_audio(self, audio):
  38. """
  39. Confirm the audio exists annd run it in a Callback
  40. :param audio: the captured audio
  41. """
  42. # if self.main_controller is not None:
  43. # self.main_controller.analyse_order(audio)
  44. if self.callback is not None:
  45. self.callback(audio)