Utils.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, audio_file=None):
  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. self.audio_stream = None
  20. if audio_file is None:
  21. # audio file not set, we need to capture a sample from the microphone
  22. with self.microphone as source:
  23. # we only need to calibrate once, before we start listening
  24. self.recognizer.adjust_for_ambient_noise(source)
  25. else:
  26. # audio file provided
  27. with sr.AudioFile(audio_file) as source:
  28. self.audio_stream = self.recognizer.record(source) # read the entire audio file
  29. def run(self):
  30. """
  31. Start the thread that listen the microphone and then give the audio to the callback method
  32. """
  33. if self.audio_stream is None:
  34. Utils.print_info("Say something!")
  35. self.stop_thread = self.recognizer.listen_in_background(self.microphone, self.callback)
  36. while not self.kill_yourself:
  37. sleep(0.1)
  38. logger.debug("kill the speech recognition process")
  39. self.stop_thread()
  40. else:
  41. self.callback(self.recognizer, self.audio_stream)
  42. def start_processing(self):
  43. """
  44. A method to start the thread
  45. """
  46. self.start()
  47. def stop_listening(self):
  48. self.kill_yourself = True
  49. def set_callback(self, callback):
  50. """
  51. set the callback method that will receive the audio stream caught by the microphone
  52. :param callback: callback method
  53. :return:
  54. """
  55. self.callback = callback