Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add flush_flag to listener to flush the recorded audio immediately without waiting for the phrase to complete. #761

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions speech_recognition/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ def snowboy_wait_for_hot_word(self, snowboy_location, snowboy_hot_word_files, so

return b"".join(frames), elapsed_time

def listen(self, source, timeout=None, phrase_time_limit=None, snowboy_configuration=None):
def listen(self, source, timeout=None, phrase_time_limit=None, snowboy_configuration=None, flush_flag=[False]):
"""
Records a single phrase from ``source`` (an ``AudioSource`` instance) into an ``AudioData`` instance, which it returns.

Expand Down Expand Up @@ -515,6 +515,11 @@ def listen(self, source, timeout=None, phrase_time_limit=None, snowboy_configura
pause_count, phrase_count = 0, 0
phrase_start_time = elapsed_time
while True:
if(flush_flag[0]):
flush_flag[0] = False
buffer == b''
break

# handle phrase being too long by cutting off the audio
elapsed_time += seconds_per_buffer
if phrase_time_limit and elapsed_time - phrase_start_time > phrase_time_limit:
Expand Down Expand Up @@ -544,7 +549,7 @@ def listen(self, source, timeout=None, phrase_time_limit=None, snowboy_configura

return AudioData(frame_data, source.SAMPLE_RATE, source.SAMPLE_WIDTH)

def listen_in_background(self, source, callback, phrase_time_limit=None):
def listen_in_background(self, source, callback, flush_flag, phrase_time_limit=None):
"""
Spawns a thread to repeatedly record phrases from ``source`` (an ``AudioSource`` instance) into an ``AudioData`` instance and call ``callback`` with that ``AudioData`` instance as soon as each phrase are detected.

Expand All @@ -561,7 +566,7 @@ def threaded_listen():
with source as s:
while running[0]:
try: # listen for 1 second, then check again if the stop function has been called
audio = self.listen(s, 1, phrase_time_limit)
audio = self.listen(s, 1, phrase_time_limit, flush_flag=flush_flag)
except WaitTimeoutError: # listening timed out, just try again
pass
else:
Expand Down