cmusphinx.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import speech_recognition as sr
  2. from kalliope.core import Utils
  3. from kalliope.stt.Utils import SpeechRecognition
  4. class Cmusphinx(SpeechRecognition):
  5. def __init__(self, callback=None, **kwargs):
  6. """
  7. Start recording the microphone and analyse audio with CMU sphinx api
  8. :param callback: The callback function to call to send the text
  9. :param kwargs:
  10. """
  11. SpeechRecognition.__init__(self)
  12. # callback function to call after the translation speech/tex
  13. self.callback = callback
  14. # start listening in the background
  15. self.stop_listening = self.start_listening(self.sphinx_callback)
  16. def sphinx_callback(self, recognizer, audio):
  17. """
  18. called from the background thread
  19. """
  20. try:
  21. captured_audio = recognizer.recognize_sphinx(audio)
  22. Utils.print_success("Sphinx Speech Recognition thinks you said %s" % captured_audio)
  23. self._analyse_audio(captured_audio)
  24. except sr.UnknownValueError:
  25. Utils.print_warning("Sphinx Speech Recognition could not understand audio")
  26. # callback anyway, we need to listen again for a new order
  27. self._analyse_audio(audio=None)
  28. except sr.RequestError as e:
  29. Utils.print_danger("Could not request results from Sphinx Speech Recognition service; {0}".format(e))
  30. # callback anyway, we need to listen again for a new order
  31. self._analyse_audio(audio=None)
  32. def _analyse_audio(self, audio):
  33. """
  34. Confirm the audio exists and run it in a Callback
  35. :param audio: the captured audio
  36. """
  37. if self.callback is not None:
  38. self.callback(audio)