audio_recorder.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. """
  2. The AudioToTextRecorder class in the provided code facilitates fast speech-to-text transcription.
  3. The class employs the faster_whisper library to transcribe the recorded audio
  4. into text using machine learning models, which can be run either on a GPU or CPU.
  5. Voice activity detection (VAD) is built in, meaning the software can automatically
  6. start or stop recording based on the presence or absence of speech.
  7. It integrates wake word detection through the pvporcupine library, allowing the
  8. software to initiate recording when a specific word or phrase is spoken.
  9. The system provides real-time feedback and can be further customized.
  10. Features:
  11. - Voice Activity Detection: Automatically starts/stops recording when speech is detected or when speech ends.
  12. - Wake Word Detection: Starts recording when a specified wake word (or words) is detected.
  13. - Event Callbacks: Customizable callbacks for when recording starts or finishes.
  14. - Fast Transcription: Returns the transcribed text from the audio as fast as possible.
  15. Author: Kolja Beigel
  16. """
  17. import pyaudio
  18. import collections
  19. import faster_whisper
  20. import torch
  21. import numpy as np
  22. import struct
  23. import pvporcupine
  24. import threading
  25. import time
  26. import logging
  27. import webrtcvad
  28. import itertools
  29. from collections import deque
  30. from halo import Halo
  31. SAMPLE_RATE = 16000
  32. BUFFER_SIZE = 512
  33. SILERO_SENSITIVITY = 0.6
  34. WEBRTC_SENSITIVITY = 3
  35. WAKE_WORDS_SENSITIVITY = 0.6
  36. TIME_SLEEP = 0.02
  37. class AudioToTextRecorder:
  38. """
  39. A class responsible for capturing audio from the microphone, detecting voice activity, and then transcribing the captured audio using the `faster_whisper` model.
  40. """
  41. def __init__(self,
  42. model: str = "tiny",
  43. language: str = "",
  44. on_recording_start = None,
  45. on_recording_stop = None,
  46. on_transcription_start = None,
  47. spinner = True,
  48. level=logging.WARNING,
  49. # Voice activation parameters
  50. silero_sensitivity: float = SILERO_SENSITIVITY,
  51. webrtc_sensitivity: int = WEBRTC_SENSITIVITY,
  52. post_speech_silence_duration: float = 0.2,
  53. min_length_of_recording: float = 1.0,
  54. min_gap_between_recordings: float = 1.0,
  55. pre_recording_buffer_duration: float = 1,
  56. on_vad_detect_start = None,
  57. on_vad_detect_stop = None,
  58. # Wake word parameters
  59. wake_words: str = "",
  60. wake_words_sensitivity: float = WAKE_WORDS_SENSITIVITY,
  61. wake_word_activation_delay: float = 0,
  62. wake_word_timeout: float = 5.0,
  63. on_wakeword_detected = None,
  64. on_wakeword_timeout = None,
  65. on_wakeword_detection_start = None,
  66. on_wakeword_detection_end = None,
  67. ):
  68. """
  69. Initializes an audio recorder and transcription and wake word detection.
  70. Args:
  71. - model (str, default="tiny"): Specifies the size of the transcription model to use or the path to a converted model directory.
  72. Valid options are 'tiny', 'tiny.en', 'base', 'base.en', 'small', 'small.en', 'medium', 'medium.en', 'large-v1', 'large-v2'.
  73. If a specific size is provided, the model is downloaded from the Hugging Face Hub.
  74. - language (str, default=""): Language code for speech-to-text engine. If not specified, the model will attempt to detect the language automatically.
  75. - on_recording_start (callable, default=None): Callback function to be called when recording of audio to be transcripted starts.
  76. - on_recording_stop (callable, default=None): Callback function to be called when recording of audio to be transcripted stops.
  77. - on_transcription_start (callable, default=None): Callback function to be called when transcription of audio to text starts.
  78. - spinner (bool, default=True): Show spinner animation with current state.
  79. - level (int, default=logging.WARNING): Logging level.
  80. - silero_sensitivity (float, default=SILERO_SENSITIVITY): Sensitivity for the Silero Voice Activity Detection model ranging from 0 (least sensitive) to 1 (most sensitive). Default is 0.5.
  81. - webrtc_sensitivity (int, default=WEBRTC_SENSITIVITY): Sensitivity for the WebRTC Voice Activity Detection engine ranging from 1 (least sensitive) to 3 (most sensitive). Default is 3.
  82. - post_speech_silence_duration (float, default=0.2): Duration in seconds of silence that must follow speech before the recording is considered to be completed. This ensures that any brief pauses during speech don't prematurely end the recording.
  83. - min_gap_between_recordings (float, default=1.0): Specifies the minimum time interval in seconds that should exist between the end of one recording session and the beginning of another to prevent rapid consecutive recordings.
  84. - min_length_of_recording (float, default=1.0): Specifies the minimum duration in seconds that a recording session should last to ensure meaningful audio capture, preventing excessively short or fragmented recordings.
  85. - pre_recording_buffer_duration (float, default=0.2): Duration in seconds for the audio buffer to maintain pre-roll audio (compensates speech activity detection latency)
  86. - wake_words (str, default=""): Comma-separated string of wake words to initiate recording. Supported wake words include:
  87. 'alexa', 'americano', 'blueberry', 'bumblebee', 'computer', 'grapefruits', 'grasshopper', 'hey google', 'hey siri', 'jarvis', 'ok google', 'picovoice', 'porcupine', 'terminator'.
  88. - wake_words_sensitivity (float, default=0.5): Sensitivity for wake word detection, ranging from 0 (least sensitive) to 1 (most sensitive). Default is 0.5.
  89. - wake_word_activation_delay (float, default=0): Duration in seconds after the start of monitoring before the system switches to wake word activation if no voice is initially detected. If set to zero, the system uses wake word activation immediately.
  90. - wake_word_timeout (float, default=5): Duration in seconds after a wake word is recognized. If no subsequent voice activity is detected within this window, the system transitions back to an inactive state, awaiting the next wake word or voice activation.
  91. - on_wakeword_detected (callable, default=None): Callback function to be called when a wake word is detected.
  92. - on_wakeword_timeout (callable, default=None): Callback function to be called when the system goes back to an inactive state after when no speech was detected after wake word activation
  93. - on_wakeword_detection_start (callable, default=None): Callback function to be called when the system starts to listen for wake words
  94. - on_wakeword_detection_end (callable, default=None): Callback function to be called when the system stops to listen for wake words (e.g. because of timeout or wake word detected)
  95. Raises:
  96. Exception: Errors related to initializing transcription model, wake word detection, or audio recording.
  97. """
  98. self.language = language
  99. self.wake_words = wake_words
  100. self.wake_word_activation_delay = wake_word_activation_delay
  101. self.wake_word_timeout = wake_word_timeout
  102. self.min_gap_between_recordings = min_gap_between_recordings
  103. self.min_length_of_recording = min_length_of_recording
  104. self.pre_recording_buffer_duration = pre_recording_buffer_duration
  105. self.post_speech_silence_duration = post_speech_silence_duration
  106. self.on_recording_start = on_recording_start
  107. self.on_recording_stop = on_recording_stop
  108. self.on_wakeword_detected = on_wakeword_detected
  109. self.on_wakeword_timeout = on_wakeword_timeout
  110. self.on_vad_detect_start = on_vad_detect_start
  111. self.on_vad_detect_stop = on_vad_detect_stop
  112. self.on_wakeword_detection_start = on_wakeword_detection_start
  113. self.on_wakeword_detection_end = on_wakeword_detection_end
  114. self.on_transcription_start = on_transcription_start
  115. self.level = level
  116. self.buffer_size = BUFFER_SIZE
  117. self.sample_rate = SAMPLE_RATE
  118. self.recording_start_time = 0
  119. self.recording_stop_time = 0
  120. self.wake_word_detect_time = 0
  121. self.silero_check_time = 0
  122. self.speech_end_silence_start = 0
  123. self.silero_sensitivity = silero_sensitivity
  124. self.listen_start = 0
  125. self.spinner = spinner
  126. self.halo = None
  127. self.state = "inactive"
  128. self.wakeword_detected = False
  129. # Initialize the logging configuration with the specified level
  130. logging.basicConfig(format='RealTimeSTT: %(message)s', level=level)
  131. # Initialize the transcription model
  132. try:
  133. self.model = faster_whisper.WhisperModel(model_size_or_path=model, device='cuda' if torch.cuda.is_available() else 'cpu')
  134. except Exception as e:
  135. logging.exception(f"Error initializing faster_whisper transcription model: {e}")
  136. raise
  137. # Setup wake word detection
  138. if wake_words:
  139. self.wake_words_list = [word.strip() for word in wake_words.lower().split(',')]
  140. sensitivity_list = [float(wake_words_sensitivity) for _ in range(len(self.wake_words_list))]
  141. try:
  142. self.porcupine = pvporcupine.create(keywords=self.wake_words_list, sensitivities=sensitivity_list)
  143. self.buffer_size = self.porcupine.frame_length
  144. self.sample_rate = self.porcupine.sample_rate
  145. except Exception as e:
  146. logging.exception(f"Error initializing porcupine wake word detection engine: {e}")
  147. raise
  148. # Setup audio recording infrastructure
  149. try:
  150. self.audio = pyaudio.PyAudio()
  151. self.stream = self.audio.open(rate=self.sample_rate, format=pyaudio.paInt16, channels=1, input=True, frames_per_buffer=self.buffer_size)
  152. except Exception as e:
  153. logging.exception(f"Error initializing pyaudio audio recording: {e}")
  154. raise
  155. # Setup voice activity detection model WebRTC
  156. try:
  157. self.webrtc_vad_model = webrtcvad.Vad()
  158. self.webrtc_vad_model.set_mode(webrtc_sensitivity)
  159. except Exception as e:
  160. logging.exception(f"Error initializing WebRTC voice activity detection engine: {e}")
  161. raise
  162. # Setup voice activity detection model Silero VAD
  163. try:
  164. self.silero_vad_model, _ = torch.hub.load(
  165. repo_or_dir="snakers4/silero-vad",
  166. model="silero_vad",
  167. verbose=False
  168. )
  169. except Exception as e:
  170. logging.exception(f"Error initializing Silero VAD voice activity detection engine: {e}")
  171. raise
  172. self.audio_buffer = collections.deque(maxlen=int((self.sample_rate // self.buffer_size) * self.pre_recording_buffer_duration))
  173. self.frames = []
  174. # Recording control flags
  175. self.is_recording = False
  176. self.is_running = True
  177. self.start_recording_on_voice_activity = False
  178. self.stop_recording_on_voice_deactivity = False
  179. # Start the recording worker thread
  180. self.recording_thread = threading.Thread(target=self._recording_worker)
  181. self.recording_thread.daemon = True
  182. self.recording_thread.start()
  183. def text(self):
  184. """
  185. Transcribes audio captured by the class instance using the `faster_whisper` model.
  186. - Waits for voice activity if not yet started recording
  187. - Waits for voice deactivity if not yet stopped recording
  188. - Transcribes the recorded audio.
  189. Returns:
  190. str: The transcription of the recorded audio or an empty string in case of an error.
  191. """
  192. self.listen_start = time.time()
  193. # If not yet started to record, wait for voice activity to initiate recording.
  194. if not self.is_recording and len(self.frames) == 0:
  195. self._set_state("listening")
  196. self._set_spinner("speak now")
  197. self.start_recording_on_voice_activity = True
  198. while not self.is_recording:
  199. time.sleep(TIME_SLEEP)
  200. # If still recording, wait for voice deactivity to finish recording.
  201. if self.is_recording:
  202. self.stop_recording_on_voice_deactivity = True
  203. while self.is_recording:
  204. time.sleep(TIME_SLEEP)
  205. # Convert the concatenated frames into text
  206. try:
  207. audio_array = np.frombuffer(b''.join(self.frames), dtype=np.int16)
  208. audio_array = audio_array.astype(np.float32) / 32768.0
  209. self.frames = []
  210. # perform transcription
  211. transcription = " ".join(seg.text for seg in self.model.transcribe(audio_array, language=self.language if self.language else None)[0]).strip()
  212. self.recording_stop_time = 0
  213. self.listen_start = 0
  214. if self.spinner and self.halo:
  215. self.halo.stop()
  216. self.halo = None
  217. self._set_state("inactive")
  218. return transcription
  219. except ValueError:
  220. logging.error("Error converting audio buffer to numpy array.")
  221. raise
  222. except faster_whisper.WhisperError as e:
  223. logging.error(f"Whisper transcription error: {e}")
  224. raise
  225. except Exception as e:
  226. logging.error(f"General transcription error: {e}")
  227. raise
  228. def start(self):
  229. """
  230. Starts recording audio directly without waiting for voice activity.
  231. """
  232. # Ensure there's a minimum interval between stopping and starting recording
  233. if time.time() - self.recording_stop_time < self.min_gap_between_recordings:
  234. logging.info("Attempted to start recording too soon after stopping.")
  235. return self
  236. logging.info("recording started")
  237. self.wakeword_detected = False
  238. self.wake_word_detect_time = 0
  239. self.frames = []
  240. self.is_recording = True
  241. self.recording_start_time = time.time()
  242. self._set_spinner("recording")
  243. self._set_state("recording")
  244. if self.halo: self.halo._interval = 100
  245. if self.on_recording_start:
  246. self.on_recording_start()
  247. return self
  248. def stop(self):
  249. """
  250. Stops recording audio.
  251. """
  252. # Ensure there's a minimum interval between starting and stopping recording
  253. if time.time() - self.recording_start_time < self.min_length_of_recording:
  254. logging.info("Attempted to stop recording too soon after starting.")
  255. return self
  256. logging.info("recording stopped")
  257. self.is_recording = False
  258. self.recording_stop_time = time.time()
  259. self._set_spinner("transcribing")
  260. self._set_state("transcribing")
  261. if self.on_recording_stop:
  262. self.on_recording_stop()
  263. return self
  264. def shutdown(self):
  265. """
  266. Safely shuts down the audio recording by stopping the recording worker and closing the audio stream.
  267. """
  268. self.is_recording = False
  269. self.is_running = False
  270. self.recording_thread.join()
  271. try:
  272. self.stream.stop_stream()
  273. self.stream.close()
  274. self.audio.terminate()
  275. except Exception as e:
  276. logging.error(f"Error closing the audio stream: {e}")
  277. def _calculate_percentile_mean(self, buffer, percentile, upper=True):
  278. """
  279. Calculates the mean of the specified percentile from the provided buffer of
  280. noise levels. If upper is True, it calculates from the upper side,
  281. otherwise from the lower side.
  282. Args:
  283. - buffer (list): The buffer containing the history of noise levels.
  284. - percentile (float): The desired percentile (0.0 <= percentile <= 1.0). E.g., 0.125 for 1/8.
  285. - upper (bool): Determines if the function considers the upper or lower portion of data.
  286. Returns:
  287. - float: The mean value of the desired portion.
  288. """
  289. sorted_buffer = sorted(buffer)
  290. index = int(len(sorted_buffer) * percentile)
  291. if upper:
  292. values = sorted_buffer[-index:] # Get values from the top
  293. else:
  294. values = sorted_buffer[:index] # Get values from the bottom
  295. if len(values) == 0:
  296. return 0.0
  297. return sum(values) / len(values)
  298. def _is_silero_speech(self, data):
  299. """
  300. Returns true if speech is detected in the provided audio data
  301. Args:
  302. data (bytes): raw bytes of audio data (1024 raw bytes with 16000 sample rate and 16 bits per sample)
  303. """
  304. audio_chunk = np.frombuffer(data, dtype=np.int16)
  305. audio_chunk = audio_chunk.astype(np.float32) / 32768.0 # Convert to float and normalize
  306. vad_prob = self.silero_vad_model(torch.from_numpy(audio_chunk), SAMPLE_RATE).item()
  307. return vad_prob > (1 - self.silero_sensitivity)
  308. def _is_webrtc_speech(self, data):
  309. """
  310. Returns true if speech is detected in the provided audio data
  311. Args:
  312. data (bytes): raw bytes of audio data (1024 raw bytes with 16000 sample rate and 16 bits per sample)
  313. """
  314. # Number of audio frames per millisecond
  315. frame_length = int(self.sample_rate * 0.01) # for 10ms frame
  316. num_frames = int(len(data) / (2 * frame_length))
  317. for i in range(num_frames):
  318. start_byte = i * frame_length * 2
  319. end_byte = start_byte + frame_length * 2
  320. frame = data[start_byte:end_byte]
  321. if self.webrtc_vad_model.is_speech(frame, self.sample_rate):
  322. return True
  323. return False
  324. def _is_voice_active(self, data):
  325. """
  326. Determine if voice is active based on the provided data.
  327. Args:
  328. data: The audio data to be checked for voice activity.
  329. Returns:
  330. bool: True if voice is active, False otherwise.
  331. """
  332. # Define a constant for the time threshold
  333. TIME_THRESHOLD = 0.1
  334. # Check if enough time has passed to reset the Silero check time
  335. if time.time() - self.silero_check_time > TIME_THRESHOLD:
  336. self.silero_check_time = 0
  337. # First quick performing check for voice activity using WebRTC
  338. if self._is_webrtc_speech(data):
  339. # If silero check time not set
  340. if self.silero_check_time == 0:
  341. self.silero_check_time = time.time()
  342. # Perform a more intensive check using Silero
  343. if self._is_silero_speech(data):
  344. return True # Voice is active
  345. return False # Voice is not active
  346. def _set_state(self, new_state):
  347. """
  348. Update the current state of the recorder and execute corresponding state-change callbacks.
  349. Args:
  350. new_state (str): The new state to set.
  351. """
  352. # Check if the state has actually changed
  353. if new_state == self.state:
  354. return
  355. # Store the current state for later comparison
  356. old_state = self.state
  357. # Update to the new state
  358. self.state = new_state
  359. # Execute callbacks based on transitioning FROM a particular state
  360. if old_state == "listening":
  361. if self.on_vad_detect_stop:
  362. self.on_vad_detect_stop()
  363. elif old_state == "wakeword":
  364. if self.on_wakeword_detection_end:
  365. self.on_wakeword_detection_end()
  366. # Execute callbacks based on transitioning TO a particular state
  367. if new_state == "listening":
  368. if self.on_vad_detect_start:
  369. self.on_vad_detect_start()
  370. elif new_state == "wakeword":
  371. if self.on_wakeword_detection_start:
  372. self.on_wakeword_detection_start()
  373. elif new_state == "transcribing":
  374. if self.on_transcription_start:
  375. self.on_transcription_start()
  376. def _set_spinner(self, text):
  377. """
  378. Update the spinner's text or create a new spinner with the provided text.
  379. Args:
  380. text (str): The text to be displayed alongside the spinner.
  381. """
  382. if self.spinner:
  383. # If the Halo spinner doesn't exist, create and start it
  384. if self.halo is None:
  385. self.halo = Halo(text=text)
  386. self.halo.start()
  387. # If the Halo spinner already exists, just update the text
  388. else:
  389. self.halo.text = text
  390. def _recording_worker(self):
  391. """
  392. The main worker method which constantly monitors the audio input for voice activity and accordingly starts/stops the recording.
  393. """
  394. was_recording = False
  395. delay_was_passed = False
  396. # Continuously monitor audio for voice activity
  397. while self.is_running:
  398. try:
  399. data = self.stream.read(self.buffer_size)
  400. except pyaudio.paInputOverflowed:
  401. logging.warning("Input overflowed. Frame dropped.")
  402. continue
  403. except Exception as e:
  404. logging.error(f"Error during recording: {e}")
  405. time.sleep(1)
  406. continue
  407. if not self.is_recording:
  408. # handle not recording state
  409. time_since_listen_start = time.time() - self.listen_start if self.listen_start else 0
  410. wake_word_activation_delay_passed = (time_since_listen_start > self.wake_word_activation_delay)
  411. # handle wake-word timeout callback
  412. if wake_word_activation_delay_passed and not delay_was_passed:
  413. if self.wake_words and self.wake_word_activation_delay:
  414. if self.on_wakeword_timeout:
  415. self.on_wakeword_timeout()
  416. delay_was_passed = wake_word_activation_delay_passed
  417. # Set state and spinner text
  418. if not self.recording_stop_time:
  419. if self.wake_words and wake_word_activation_delay_passed and not self.wakeword_detected:
  420. self._set_state("wakeword")
  421. if self.spinner and self.halo:
  422. self.halo.text = f"say {self.wake_words}"
  423. self.halo._interval = 500
  424. else:
  425. if self.listen_start:
  426. self._set_state("listening")
  427. else:
  428. self._set_state("inactive")
  429. if self.spinner and self.halo:
  430. self.halo.text = "speak now"
  431. self.halo._interval = 200
  432. # Detect wake words if applicable
  433. if self.wake_words and wake_word_activation_delay_passed:
  434. try:
  435. pcm = struct.unpack_from("h" * self.buffer_size, data)
  436. wakeword_index = self.porcupine.process(pcm)
  437. except struct.error:
  438. logging.error("Error unpacking audio data for wake word processing.")
  439. continue
  440. except Exception as e:
  441. logging.error(f"Wake word processing error: {e}")
  442. continue
  443. # If a wake word is detected
  444. if wakeword_index >= 0:
  445. # Removing the wake word from the recording
  446. samples_for_0_1_sec = int(self.sample_rate * 0.1)
  447. start_index = max(0, len(self.audio_buffer) - samples_for_0_1_sec)
  448. temp_samples = collections.deque(itertools.islice(self.audio_buffer, start_index, None))
  449. self.audio_buffer.clear()
  450. self.audio_buffer.extend(temp_samples)
  451. self.wake_word_detect_time = time.time()
  452. self.wakeword_detected = True
  453. if self.on_wakeword_detected:
  454. self.on_wakeword_detected()
  455. # Check for voice activity to trigger the start of recording
  456. if ((not self.wake_words or not wake_word_activation_delay_passed) and self.start_recording_on_voice_activity) or self.wakeword_detected:
  457. if self._is_voice_active(data):
  458. logging.info("voice activity detected")
  459. self.start()
  460. if self.is_recording:
  461. self.start_recording_on_voice_activity = False
  462. # Add the buffered audio to the recording frames
  463. self.frames.extend(list(self.audio_buffer))
  464. self.silero_vad_model.reset_states()
  465. self.speech_end_silence_start = 0
  466. else:
  467. # If we are currently recording
  468. # Stop the recording if silence is detected after speech
  469. if self.stop_recording_on_voice_deactivity:
  470. if not self._is_webrtc_speech(data):
  471. # Voice deactivity was detected, so we start measuring silence time before stopping recording
  472. if self.speech_end_silence_start == 0:
  473. self.speech_end_silence_start = time.time()
  474. else:
  475. self.speech_end_silence_start = 0
  476. # Wait for silence to stop recording after speech
  477. if self.speech_end_silence_start and time.time() - self.speech_end_silence_start > self.post_speech_silence_duration:
  478. logging.info("voice deactivity detected")
  479. self.stop()
  480. if not self.is_recording and was_recording:
  481. # Reset after stopping recording to ensure clean state
  482. self.stop_recording_on_voice_deactivity = False
  483. if time.time() - self.silero_check_time > 0.1:
  484. self.silero_check_time = 0
  485. if self.wake_word_detect_time and time.time() - self.wake_word_detect_time > self.wake_word_timeout:
  486. self.wake_word_detect_time = 0
  487. if self.wakeword_detected and self.on_wakeword_timeout:
  488. self.on_wakeword_timeout()
  489. self.wakeword_detected = False
  490. if self.is_recording:
  491. self.frames.append(data)
  492. self.audio_buffer.append(data)
  493. was_recording = self.is_recording
  494. time.sleep(TIME_SLEEP)
  495. def __del__(self):
  496. """
  497. Destructor method ensures safe shutdown of the recorder when the instance is destroyed.
  498. """
  499. self.shutdown()