MicrophoneStream.py
Go to the documentation of this file.
1 import pyaudio
2 from six.moves import queue
3 
4 # Audio recording parameters
5 RATE = 16000
6 CHUNK = 1600
7 
8 
9 class MicrophoneStream(object):
10  """Opens a recording stream as a generator yielding the audio chunks."""
11  def __init__(self, rate=RATE, chunk=CHUNK):
12  self._rate = rate
13  self._chunk = chunk
14 
15  # Create a thread-safe buffer of audio data
16  self._buff = queue.Queue()
17  self.closed = True
18 
19  def __enter__(self):
20  self._audio_interface = pyaudio.PyAudio()
21  self._audio_stream = self._audio_interface.open(
22  format=pyaudio.paInt16,
23  channels=1, rate=self._rate,
24  input=True, frames_per_buffer=self._chunk,
25  # Run the audio stream asynchronously to fill the buffer object.
26  # This is necessary so that the input device's buffer doesn't
27  # overflow while the calling thread makes network requests, etc.
28  stream_callback=self._fill_buffer,
29  )
30 
31  self.closed = False
32 
33  return self
34 
35  def __exit__(self, type, value, traceback):
36  self._audio_stream.stop_stream()
37  self._audio_stream.close()
38  self.closed = True
39  # Signal the generator to terminate so that the client's
40  # streaming_recognize method will not block the process termination.
41  self._buff.put(None)
42  self._audio_interface.terminate()
43 
44  def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
45  """Continuously collect data from the audio stream, into the buffer."""
46  self._buff.put(in_data)
47  return None, pyaudio.paContinue
48 
49  def generator(self):
50  while not self.closed:
51  # Use a blocking get() to ensure there's at least one chunk of
52  # data, and stop iteration if the chunk is None, indicating the
53  # end of the audio stream.
54  chunk = self._buff.get()
55  if chunk is None:
56  return
57  data = [chunk]
58 
59  # Now consume whatever other data's still buffered.
60  while True:
61  try:
62  chunk = self._buff.get(block=False)
63  if chunk is None:
64  return
65  data.append(chunk)
66  except queue.Empty:
67  break
68 
69  yield b''.join(data)
def _fill_buffer(self, in_data, frame_count, time_info, status_flags)
def __init__(self, rate=RATE, chunk=CHUNK)
def __exit__(self, type, value, traceback)


dialogflow_ros
Author(s): Anas Abou Allaban
autogenerated on Mon Jun 10 2019 13:02:59