audio_recorder.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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. - on_vad_detect_start (callable, default=None): Callback function to be called when the system listens for voice activity.
  87. - on_vad_detect_stop (callable, default=None): Callback function to be called when the system stops listening for voice activity.
  88. - wake_words (str, default=""): Comma-separated string of wake words to initiate recording. Supported wake words include:
  89. 'alexa', 'americano', 'blueberry', 'bumblebee', 'computer', 'grapefruits', 'grasshopper', 'hey google', 'hey siri', 'jarvis', 'ok google', 'picovoice', 'porcupine', 'terminator'.
  90. - 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.
  91. - 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.
  92. - 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.
  93. - on_wakeword_detected (callable, default=None): Callback function to be called when a wake word is detected.
  94. - 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
  95. - on_wakeword_detection_start (callable, default=None): Callback function to be called when the system starts to listen for wake words
  96. - 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)
  97. Raises:
  98. Exception: Errors related to initializing transcription model, wake word detection, or audio recording.
  99. """
  100. self.language = language
  101. self.wake_words = wake_words
  102. self.wake_word_activation_delay = wake_word_activation_delay
  103. self.wake_word_timeout = wake_word_timeout
  104. self.min_gap_between_recordings = min_gap_between_recordings
  105. self.min_length_of_recording = min_length_of_recording
  106. self.pre_recording_buffer_duration = pre_recording_buffer_duration
  107. self.post_speech_silence_duration = post_speech_silence_duration
  108. self.on_recording_start = on_recording_start
  109. self.on_recording_stop = on_recording_stop
  110. self.on_wakeword_detected = on_wakeword_detected
  111. self.on_wakeword_timeout = on_wakeword_timeout
  112. self.on_vad_detect_start = on_vad_detect_start
  113. self.on_vad_detect_stop = on_vad_detect_stop
  114. self.on_wakeword_detection_start = on_wakeword_detection_start
  115. self.on_wakeword_detection_end = on_wakeword_detection_end
  116. self.on_transcription_start = on_transcription_start
  117. self.level = level
  118. self.buffer_size = BUFFER_SIZE
  119. self.sample_rate = SAMPLE_RATE
  120. self.recording_start_time = 0
  121. self.recording_stop_time = 0
  122. self.wake_word_detect_time = 0
  123. self.silero_check_time = 0
  124. self.speech_end_silence_start = 0
  125. self.silero_sensitivity = silero_sensitivity
  126. self.listen_start = 0
  127. self.spinner = spinner
  128. self.halo = None
  129. self.state = "inactive"
  130. self.wakeword_detected = False
  131. # Initialize the logging configuration with the specified level
  132. logging.basicConfig(format='RealTimeSTT: %(message)s', level=level)
  133. # Initialize the transcription model
  134. try:
  135. self.model = faster_whisper.WhisperModel(model_size_or_path=model, device='cuda' if torch.cuda.is_available() else 'cpu')
  136. except Exception as e:
  137. logging.exception(f"Error initializing faster_whisper transcription model: {e}")
  138. raise
  139. # Setup wake word detection
  140. if wake_words:
  141. self.wake_words_list = [word.strip() for word in wake_words.lower().split(',')]
  142. sensitivity_list = [float(wake_words_sensitivity) for _ in range(len(self.wake_words_list))]
  143. try:
  144. self.porcupine = pvporcupine.create(keywords=self.wake_words_list, sensitivities=sensitivity_list)
  145. self.buffer_size = self.porcupine.frame_length
  146. self.sample_rate = self.porcupine.sample_rate
  147. except Exception as e:
  148. logging.exception(f"Error initializing porcupine wake word detection engine: {e}")
  149. raise
  150. # Setup audio recording infrastructure
  151. try:
  152. self.audio = pyaudio.PyAudio()
  153. self.stream = self.audio.open(rate=self.sample_rate, format=pyaudio.paInt16, channels=1, input=True, frames_per_buffer=self.buffer_size)
  154. except Exception as e:
  155. logging.exception(f"Error initializing pyaudio audio recording: {e}")
  156. raise
  157. # Setup voice activity detection model WebRTC
  158. try:
  159. self.webrtc_vad_model = webrtcvad.Vad()
  160. self.webrtc_vad_model.set_mode(webrtc_sensitivity)
  161. except Exception as e:
  162. logging.exception(f"Error initializing WebRTC voice activity detection engine: {e}")
  163. raise
  164. # Setup voice activity detection model Silero VAD
  165. try:
  166. self.silero_vad_model, _ = torch.hub.load(
  167. repo_or_dir="snakers4/silero-vad",
  168. model="silero_vad",
  169. verbose=False
  170. )
  171. except Exception as e:
  172. logging.exception(f"Error initializing Silero VAD voice activity detection engine: {e}")
  173. raise
  174. self.audio_buffer = collections.deque(maxlen=int((self.sample_rate // self.buffer_size) * self.pre_recording_buffer_duration))
  175. self.frames = []
  176. # Recording control flags
  177. self.is_recording = False
  178. self.is_running = True
  179. self.start_recording_on_voice_activity = False
  180. self.stop_recording_on_voice_deactivity = False
  181. # Start the recording worker thread
  182. self.recording_thread = threading.Thread(target=self._recording_worker)
  183. self.recording_thread.daemon = True
  184. self.recording_thread.start()
  185. def text(self):
  186. """
  187. Transcribes audio captured by the class instance using the `faster_whisper` model.
  188. - Waits for voice activity if not yet started recording
  189. - Waits for voice deactivity if not yet stopped recording
  190. - Transcribes the recorded audio.
  191. Returns:
  192. str: The transcription of the recorded audio or an empty string in case of an error.
  193. """
  194. self.listen_start = time.time()
  195. # If not yet started to record, wait for voice activity to initiate recording.
  196. if not self.is_recording and len(self.frames) == 0:
  197. self._set_state("listening")
  198. self.start_recording_on_voice_activity = True
  199. while not self.is_recording:
  200. time.sleep(TIME_SLEEP)
  201. # If still recording, wait for voice deactivity to finish recording.
  202. if self.is_recording:
  203. self.stop_recording_on_voice_deactivity = True
  204. while self.is_recording:
  205. time.sleep(TIME_SLEEP)
  206. # Convert the concatenated frames into text
  207. try:
  208. audio_array = np.frombuffer(b''.join(self.frames), dtype=np.int16)
  209. audio_array = audio_array.astype(np.float32) / 32768.0
  210. self.frames = []
  211. # perform transcription
  212. transcription = " ".join(seg.text for seg in self.model.transcribe(audio_array, language=self.language if self.language else None)[0]).strip()
  213. self.recording_stop_time = 0
  214. self.listen_start = 0
  215. self._set_state("inactive")
  216. return transcription
  217. except ValueError:
  218. logging.error("Error converting audio buffer to numpy array.")
  219. raise
  220. except faster_whisper.WhisperError as e:
  221. logging.error(f"Whisper transcription error: {e}")
  222. raise
  223. except Exception as e:
  224. logging.error(f"General transcription error: {e}")
  225. raise
  226. def start(self):
  227. """
  228. Starts recording audio directly without waiting for voice activity.
  229. """
  230. # Ensure there's a minimum interval between stopping and starting recording
  231. if time.time() - self.recording_stop_time < self.min_gap_between_recordings:
  232. logging.info("Attempted to start recording too soon after stopping.")
  233. return self
  234. logging.info("recording started")
  235. self.wakeword_detected = False
  236. self.wake_word_detect_time = 0
  237. self.frames = []
  238. self.is_recording = True
  239. self.recording_start_time = time.time()
  240. self._set_state("recording")
  241. if self.on_recording_start:
  242. self.on_recording_start()
  243. return self
  244. def stop(self):
  245. """
  246. Stops recording audio.
  247. """
  248. # Ensure there's a minimum interval between starting and stopping recording
  249. if time.time() - self.recording_start_time < self.min_length_of_recording:
  250. logging.info("Attempted to stop recording too soon after starting.")
  251. return self
  252. logging.info("recording stopped")
  253. self.is_recording = False
  254. self.recording_stop_time = time.time()
  255. self._set_state("transcribing")
  256. if self.on_recording_stop:
  257. self.on_recording_stop()
  258. return self
  259. def shutdown(self):
  260. """
  261. Safely shuts down the audio recording by stopping the recording worker and closing the audio stream.
  262. """
  263. self.is_recording = False
  264. self.is_running = False
  265. self.recording_thread.join()
  266. try:
  267. self.stream.stop_stream()
  268. self.stream.close()
  269. self.audio.terminate()
  270. except Exception as e:
  271. logging.error(f"Error closing the audio stream: {e}")
  272. def _calculate_percentile_mean(self, buffer, percentile, upper=True):
  273. """
  274. Calculates the mean of the specified percentile from the provided buffer of
  275. noise levels. If upper is True, it calculates from the upper side,
  276. otherwise from the lower side.
  277. Args:
  278. - buffer (list): The buffer containing the history of noise levels.
  279. - percentile (float): The desired percentile (0.0 <= percentile <= 1.0). E.g., 0.125 for 1/8.
  280. - upper (bool): Determines if the function considers the upper or lower portion of data.
  281. Returns:
  282. - float: The mean value of the desired portion.
  283. """
  284. sorted_buffer = sorted(buffer)
  285. index = int(len(sorted_buffer) * percentile)
  286. if upper:
  287. values = sorted_buffer[-index:] # Get values from the top
  288. else:
  289. values = sorted_buffer[:index] # Get values from the bottom
  290. if len(values) == 0:
  291. return 0.0
  292. return sum(values) / len(values)
  293. def _is_silero_speech(self, data):
  294. """
  295. Returns true if speech is detected in the provided audio data
  296. Args:
  297. data (bytes): raw bytes of audio data (1024 raw bytes with 16000 sample rate and 16 bits per sample)
  298. """
  299. audio_chunk = np.frombuffer(data, dtype=np.int16)
  300. audio_chunk = audio_chunk.astype(np.float32) / 32768.0 # Convert to float and normalize
  301. vad_prob = self.silero_vad_model(torch.from_numpy(audio_chunk), SAMPLE_RATE).item()
  302. return vad_prob > (1 - self.silero_sensitivity)
  303. def _is_webrtc_speech(self, data):
  304. """
  305. Returns true if speech is detected in the provided audio data
  306. Args:
  307. data (bytes): raw bytes of audio data (1024 raw bytes with 16000 sample rate and 16 bits per sample)
  308. """
  309. # Number of audio frames per millisecond
  310. frame_length = int(self.sample_rate * 0.01) # for 10ms frame
  311. num_frames = int(len(data) / (2 * frame_length))
  312. for i in range(num_frames):
  313. start_byte = i * frame_length * 2
  314. end_byte = start_byte + frame_length * 2
  315. frame = data[start_byte:end_byte]
  316. if self.webrtc_vad_model.is_speech(frame, self.sample_rate):
  317. return True
  318. return False
  319. def _is_voice_active(self, data):
  320. """
  321. Determine if voice is active based on the provided data.
  322. Args:
  323. data: The audio data to be checked for voice activity.
  324. Returns:
  325. bool: True if voice is active, False otherwise.
  326. """
  327. # Define a constant for the time threshold
  328. TIME_THRESHOLD = 0.1
  329. # Check if enough time has passed to reset the Silero check time
  330. if time.time() - self.silero_check_time > TIME_THRESHOLD:
  331. self.silero_check_time = 0
  332. # First quick performing check for voice activity using WebRTC
  333. if self._is_webrtc_speech(data):
  334. # If silero check time not set
  335. if self.silero_check_time == 0:
  336. self.silero_check_time = time.time()
  337. # Perform a more intensive check using Silero
  338. if self._is_silero_speech(data):
  339. return True # Voice is active
  340. return False # Voice is not active
  341. def _set_state(self, new_state):
  342. """
  343. Update the current state of the recorder and execute corresponding state-change callbacks.
  344. Args:
  345. new_state (str): The new state to set.
  346. """
  347. # Check if the state has actually changed
  348. if new_state == self.state:
  349. return
  350. # Store the current state for later comparison
  351. old_state = self.state
  352. # Update to the new state
  353. self.state = new_state
  354. # Execute callbacks based on transitioning FROM a particular state
  355. if old_state == "listening":
  356. if self.on_vad_detect_stop:
  357. self.on_vad_detect_stop()
  358. elif old_state == "wakeword":
  359. if self.on_wakeword_detection_end:
  360. self.on_wakeword_detection_end()
  361. # Execute callbacks based on transitioning TO a particular state
  362. if new_state == "listening":
  363. if self.on_vad_detect_start:
  364. self.on_vad_detect_start()
  365. self._set_spinner("speak now")
  366. self.halo._interval = 250
  367. elif new_state == "wakeword":
  368. if self.on_wakeword_detection_start:
  369. self.on_wakeword_detection_start()
  370. self._set_spinner(f"say {self.wake_words}")
  371. self.halo._interval = 500
  372. elif new_state == "transcribing":
  373. if self.on_transcription_start:
  374. self.on_transcription_start()
  375. self._set_spinner("transcribing")
  376. self.halo._interval = 50
  377. elif new_state == "recording":
  378. self._set_spinner("recording")
  379. self.halo._interval = 100
  380. elif new_state == "inactive":
  381. if self.spinner and self.halo:
  382. self.halo.stop()
  383. self.halo = None
  384. def _set_spinner(self, text):
  385. """
  386. Update the spinner's text or create a new spinner with the provided text.
  387. Args:
  388. text (str): The text to be displayed alongside the spinner.
  389. """
  390. if self.spinner:
  391. # If the Halo spinner doesn't exist, create and start it
  392. if self.halo is None:
  393. self.halo = Halo(text=text)
  394. self.halo.start()
  395. # If the Halo spinner already exists, just update the text
  396. else:
  397. self.halo.text = text
  398. def _recording_worker(self):
  399. """
  400. The main worker method which constantly monitors the audio input for voice activity and accordingly starts/stops the recording.
  401. """
  402. was_recording = False
  403. delay_was_passed = False
  404. # Continuously monitor audio for voice activity
  405. while self.is_running:
  406. try:
  407. data = self.stream.read(self.buffer_size)
  408. except pyaudio.paInputOverflowed:
  409. logging.warning("Input overflowed. Frame dropped.")
  410. continue
  411. except Exception as e:
  412. logging.error(f"Error during recording: {e}")
  413. time.sleep(1)
  414. continue
  415. if not self.is_recording:
  416. # handle not recording state
  417. time_since_listen_start = time.time() - self.listen_start if self.listen_start else 0
  418. wake_word_activation_delay_passed = (time_since_listen_start > self.wake_word_activation_delay)
  419. # handle wake-word timeout callback
  420. if wake_word_activation_delay_passed and not delay_was_passed:
  421. if self.wake_words and self.wake_word_activation_delay:
  422. if self.on_wakeword_timeout:
  423. self.on_wakeword_timeout()
  424. delay_was_passed = wake_word_activation_delay_passed
  425. # Set state and spinner text
  426. if not self.recording_stop_time:
  427. if self.wake_words and wake_word_activation_delay_passed and not self.wakeword_detected:
  428. self._set_state("wakeword")
  429. else:
  430. if self.listen_start:
  431. self._set_state("listening")
  432. else:
  433. self._set_state("inactive")
  434. # Detect wake words if applicable
  435. if self.wake_words and wake_word_activation_delay_passed:
  436. try:
  437. pcm = struct.unpack_from("h" * self.buffer_size, data)
  438. wakeword_index = self.porcupine.process(pcm)
  439. except struct.error:
  440. logging.error("Error unpacking audio data for wake word processing.")
  441. continue
  442. except Exception as e:
  443. logging.error(f"Wake word processing error: {e}")
  444. continue
  445. # If a wake word is detected
  446. if wakeword_index >= 0:
  447. # Removing the wake word from the recording
  448. samples_for_0_1_sec = int(self.sample_rate * 0.1)
  449. start_index = max(0, len(self.audio_buffer) - samples_for_0_1_sec)
  450. temp_samples = collections.deque(itertools.islice(self.audio_buffer, start_index, None))
  451. self.audio_buffer.clear()
  452. self.audio_buffer.extend(temp_samples)
  453. self.wake_word_detect_time = time.time()
  454. self.wakeword_detected = True
  455. if self.on_wakeword_detected:
  456. self.on_wakeword_detected()
  457. # Check for voice activity to trigger the start of recording
  458. if ((not self.wake_words or not wake_word_activation_delay_passed) and self.start_recording_on_voice_activity) or self.wakeword_detected:
  459. if self._is_voice_active(data):
  460. logging.info("voice activity detected")
  461. self.start()
  462. if self.is_recording:
  463. self.start_recording_on_voice_activity = False
  464. # Add the buffered audio to the recording frames
  465. self.frames.extend(list(self.audio_buffer))
  466. self.silero_vad_model.reset_states()
  467. self.speech_end_silence_start = 0
  468. else:
  469. # If we are currently recording
  470. # Stop the recording if silence is detected after speech
  471. if self.stop_recording_on_voice_deactivity:
  472. if not self._is_webrtc_speech(data):
  473. # Voice deactivity was detected, so we start measuring silence time before stopping recording
  474. if self.speech_end_silence_start == 0:
  475. self.speech_end_silence_start = time.time()
  476. else:
  477. self.speech_end_silence_start = 0
  478. # Wait for silence to stop recording after speech
  479. if self.speech_end_silence_start and time.time() - self.speech_end_silence_start > self.post_speech_silence_duration:
  480. logging.info("voice deactivity detected")
  481. self.stop()
  482. if not self.is_recording and was_recording:
  483. # Reset after stopping recording to ensure clean state
  484. self.stop_recording_on_voice_deactivity = False
  485. if time.time() - self.silero_check_time > 0.1:
  486. self.silero_check_time = 0
  487. if self.wake_word_detect_time and time.time() - self.wake_word_detect_time > self.wake_word_timeout:
  488. self.wake_word_detect_time = 0
  489. if self.wakeword_detected and self.on_wakeword_timeout:
  490. self.on_wakeword_timeout()
  491. self.wakeword_detected = False
  492. if self.is_recording:
  493. self.frames.append(data)
  494. self.audio_buffer.append(data)
  495. was_recording = self.is_recording
  496. time.sleep(TIME_SLEEP)
  497. def __del__(self):
  498. """
  499. Destructor method ensures safe shutdown of the recorder when the instance is destroyed.
  500. """
  501. self.shutdown()