cmusphinx.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. # give the audio file path to process directly to the mother class if exist
  12. SpeechRecognition.__init__(self, kwargs.get('audio_file_path', None))
  13. # callback function to call after the translation speech/tex
  14. self.main_controller_callback = callback
  15. self.language = kwargs.get('language', "en-US")
  16. # start listening in the background
  17. self.set_callback(self.sphinx_callback)
  18. # start processing, record a sample from the microphone if no audio file path provided, else read the file
  19. self.start_processing()
  20. def sphinx_callback(self, recognizer, audio):
  21. """
  22. called from the background thread
  23. """
  24. try:
  25. captured_audio = recognizer.recognize_sphinx(audio, language=self.language)
  26. Utils.print_success("Sphinx Speech Recognition thinks you said %s" % captured_audio)
  27. self._analyse_audio(captured_audio)
  28. except sr.UnknownValueError:
  29. Utils.print_warning("Sphinx Speech Recognition could not understand audio")
  30. # callback anyway, we need to listen again for a new order
  31. self._analyse_audio(audio_to_text=None)
  32. except sr.RequestError as e:
  33. Utils.print_danger("Could not request results from Sphinx Speech Recognition service; {0}".format(e))
  34. # callback anyway, we need to listen again for a new order
  35. self._analyse_audio(audio_to_text=None)
  36. # stop listening for an audio
  37. self.stop_listening()
  38. def _analyse_audio(self, audio_to_text):
  39. """
  40. Confirm the audio exists and run it in a Callback
  41. :param audio_to_text: the captured audio
  42. """
  43. if self.main_controller_callback is not None:
  44. self.main_controller_callback(audio_to_text)