feed_audio.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. if __name__ == "__main__":
  2. import threading
  3. import pyaudio
  4. from RealtimeSTT import AudioToTextRecorder
  5. CHUNK = 1024
  6. FORMAT = pyaudio.paInt16
  7. CHANNELS = 1
  8. RATE = 16000
  9. recorder = AudioToTextRecorder(
  10. use_microphone=False,
  11. spinner=False
  12. )
  13. stop_event = threading.Event()
  14. def feed_audio_thread():
  15. p = pyaudio.PyAudio()
  16. stream = p.open(
  17. format=FORMAT,
  18. channels=CHANNELS,
  19. rate=RATE,
  20. input=True,
  21. frames_per_buffer=CHUNK
  22. )
  23. try:
  24. print("Speak now")
  25. while not stop_event.is_set():
  26. data = stream.read(CHUNK)
  27. recorder.feed_audio(data)
  28. except Exception as e:
  29. print(f"feed_audio_thread encountered an error: {e}")
  30. finally:
  31. stream.stop_stream()
  32. stream.close()
  33. p.terminate()
  34. print("Audio stream closed.")
  35. def recorder_transcription_thread():
  36. def process_text(full_sentence):
  37. print("Transcribed text:", full_sentence)
  38. if "stop recording" in full_sentence.lower():
  39. print("Stop command detected. Stopping threads...")
  40. stop_event.set()
  41. recorder.abort()
  42. try:
  43. while not stop_event.is_set():
  44. recorder.text(process_text)
  45. except Exception as e:
  46. print(f"transcription_thread encountered an error: {e}")
  47. finally:
  48. print("Transcription thread exiting.")
  49. audio_thread = threading.Thread(target=feed_audio_thread)
  50. audio_thread.daemon = False
  51. audio_thread.start()
  52. transcription_thread = threading.Thread(target=recorder_transcription_thread)
  53. transcription_thread.daemon = False
  54. transcription_thread.start()
  55. audio_thread.join()
  56. transcription_thread.join()
  57. print("Recording and transcription have stopped.")
  58. recorder.shutdown()