Utils.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from threading import Thread
  2. from time import sleep
  3. import logging
  4. import speech_recognition as sr
  5. from kalliope import Utils
  6. logging.basicConfig()
  7. logger = logging.getLogger("kalliope")
  8. class SpeechRecognition(Thread):
  9. def __init__(self):
  10. """
  11. Thread used to caught n audio from the microphone and pass it to a callback method
  12. """
  13. super(SpeechRecognition, self).__init__()
  14. self.recognizer = sr.Recognizer()
  15. self.microphone = sr.Microphone()
  16. self.callback = None
  17. self.stop_thread = None
  18. self.kill_yourself = False
  19. with self.microphone as source:
  20. # we only need to calibrate once, before we start listening
  21. self.recognizer.adjust_for_ambient_noise(source)
  22. def run(self):
  23. """
  24. Start the thread that listen the microphone and then give the audio to the callback method
  25. """
  26. Utils.print_info("Say something!")
  27. self.stop_thread = self.recognizer.listen_in_background(self.microphone, self.callback)
  28. while not self.kill_yourself:
  29. sleep(0.1)
  30. logger.debug("kill the speech recognition process")
  31. self.stop_thread()
  32. def start_listening(self):
  33. """
  34. A method to start the thread
  35. """
  36. self.start()
  37. def stop_listening(self):
  38. self.kill_yourself = True
  39. def set_callback(self, callback):
  40. """
  41. set the callback method that will receive the audio stream caught by the microphone
  42. :param callback: callback method
  43. :return:
  44. """
  45. self.callback = callback