From 904bd7168e73014fe608db7e999234e019bdf11b Mon Sep 17 00:00:00 2001 From: Matthew Scholefield Date: Sat, 26 Jan 2019 16:54:06 -0600 Subject: [PATCH] Add exception_on_overflow=False to pyaudio.Stream.read This resolves some issues with reading streams on certain platforms (#59) This also removes the read_divisor in favor of a wrapper for pyaudio which slightly simplifies the code --- runner/precise_runner/runner.py | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/runner/precise_runner/runner.py b/runner/precise_runner/runner.py index 3a50bdc..604571b 100644 --- a/runner/precise_runner/runner.py +++ b/runner/precise_runner/runner.py @@ -154,7 +154,6 @@ class PreciseRunner(object): self.on_prediction = on_prediction self.on_activation = on_activation self.chunk_size = engine.chunk_size - self.read_divisor = 1 self.pa = None self.thread = None @@ -163,18 +162,14 @@ class PreciseRunner(object): self.detector = TriggerDetector(self.chunk_size, sensitivity, trigger_level) atexit.register(self.stop) - def _calc_read_divisor(self): + def _wrap_stream_read(self, stream): """ pyaudio.Stream.read takes samples as n, not bytes - so read(n) should be read(n // sample_depth + so read(n) should be read(n // sample_depth) """ - try: - import pyaudio - if isinstance(self.stream, pyaudio.Stream): - return 2 - except ImportError: - pass - return 1 + import pyaudio + if getattr(stream.read, '__func__', None) is pyaudio.Stream.read: + stream.read = lambda x: pyaudio.Stream.read(stream, x // 2, False) def start(self): """Start listening from stream""" @@ -185,7 +180,7 @@ class PreciseRunner(object): 16000, 1, paInt16, True, frames_per_buffer=self.chunk_size ) - self.read_divisor = self._calc_read_divisor() + self._wrap_stream_read(self.stream) self.engine.start() self.running = True @@ -219,7 +214,7 @@ class PreciseRunner(object): def _handle_predictions(self): """Continuously check Precise process output""" while self.running: - chunk = self.stream.read(self.chunk_size // self.read_divisor) + chunk = self.stream.read(self.chunk_size) if self.is_paused: continue