Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. if True: yield 1
  2.  
  3. import pyaudio
  4. from six.moves import queue
  5.  
  6. # Audio recording parameters
  7. RATE = 16000
  8. CHUNK = int(RATE / 10) # 100ms
  9.  
  10.  
  11. class MicrophoneStream(object):
  12. """Opens a recording stream as a generator yielding the audio chunks."""
  13. def __init__(self, rate, chunk, audio):
  14. self._rate = rate
  15. self._chunk = chunk
  16. self._audio_interface = audio
  17.  
  18. # Create a thread-safe buffer of audio data
  19. self._buff = queue.Queue()
  20. self.closed = True
  21.  
  22. def __enter__(self):
  23. self._audio_stream = self._audio_interface.open(
  24. format=pyaudio.paInt16,
  25. channels=1, rate=self._rate,
  26. input=True, frames_per_buffer=self._chunk,
  27. stream_callback=self._fill_buffer,
  28. )
  29.  
  30. self.closed = False
  31.  
  32. return self
  33.  
  34. def __exit__(self, type, value, traceback):
  35. self._audio_stream.stop_stream()
  36. self._audio_stream.close()
  37. self.closed = True
  38. # Signal the generator to terminate so that the client's
  39. # streaming_recognize method will not block the process termination.
  40. self._buff.put(None)
  41. self._audio_interface.terminate()
  42.  
  43. def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
  44. """Continuously collect data from the audio stream, into the buffer."""
  45. self._buff.put(in_data)
  46. return None, pyaudio.paContinue
  47.  
  48. def generator(self):
  49. while not self.closed:
  50. # Use a blocking get() to ensure there's at least one chunk of
  51. # data, and stop iteration if the chunk is None, indicating the
  52. # end of the audio stream.
  53. chunk = self._buff.get()
  54. if chunk is None:
  55. return
  56. data = [chunk]
  57.  
  58. # Now consume whatever other data's still buffered.
  59. while True:
  60. try:
  61. chunk = self._buff.get(block=False)
  62. if chunk is None:
  63. return
  64. data.append(chunk)
  65. except queue.Empty:
  66. break
  67.  
  68. yield b''.join(data)
  69.  
  70.  
  71. p = pyaudio.PyAudio()
  72.  
  73. outputStream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, output=True)
  74.  
  75. with MicrophoneStream(RATE, CHUNK, p) as inputStream:
  76. for data in inputStream.generator():
  77. outputStream.write(data)
  78. print('looping')
  79.  
  80.  
  81. outputStream.stop_stream()
  82. outputStream.close()
  83. p.terminate()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement