Python sounddevice.InputStream() Examples
The following are 7
code examples of sounddevice.InputStream().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sounddevice
, or try the search function
.
Example #1
Source File: __init__.py From platypush with MIT License | 7 votes |
def __init__(self, input_device: Optional[Union[int, str]] = None, hotword: Optional[str] = None, hotwords: Optional[List[str]] = None, conversation_timeout: Optional[float] = 10.0, block_duration: float = 1.0): """ :param input_device: PortAudio device index or name that will be used for recording speech (default: default system audio input device). :param hotword: When this word is detected, the plugin will trigger a :class:`platypush.message.event.stt.HotwordDetectedEvent` instead of a :class:`platypush.message.event.stt.SpeechDetectedEvent` event. You can use these events for hooking other assistants. :param hotwords: Use a list of hotwords instead of a single one. :param conversation_timeout: If ``hotword`` or ``hotwords`` are set and ``conversation_timeout`` is set, the next speech detected event will trigger a :class:`platypush.message.event.stt.ConversationDetectedEvent` instead of a :class:`platypush.message.event.stt.SpeechDetectedEvent` event. You can hook custom hooks here to run any logic depending on the detected speech - it can emulate a kind of "OK, Google. Turn on the lights" interaction without using an external assistant (default: 10 seconds). :param block_duration: Duration of the acquired audio blocks (default: 1 second). """ super().__init__() self.input_device = input_device self.conversation_timeout = conversation_timeout self.block_duration = block_duration self.hotwords = set(hotwords or []) if hotword: self.hotwords = {hotword} self._conversation_event = threading.Event() self._input_stream: Optional[sd.InputStream] = None self._recording_thread: Optional[threading.Thread] = None self._detection_thread: Optional[threading.Thread] = None self._audio_queue: Optional[queue.Queue] = None self._current_text = ''
Example #2
Source File: asyncio_coroutines.py From python-sounddevice with MIT License | 6 votes |
def record_buffer(buffer, **kwargs): loop = asyncio.get_event_loop() event = asyncio.Event() idx = 0 def callback(indata, frame_count, time_info, status): nonlocal idx if status: print(status) remainder = len(buffer) - idx if remainder == 0: loop.call_soon_threadsafe(event.set) raise sd.CallbackStop indata = indata[:remainder] buffer[idx:idx + len(indata)] = indata idx += len(indata) stream = sd.InputStream(callback=callback, dtype=buffer.dtype, channels=buffer.shape[1], **kwargs) with stream: await event.wait()
Example #3
Source File: __init__.py From platypush with MIT License | 5 votes |
def recording_thread(self, block_duration: Optional[float] = None, block_size: Optional[int] = None, input_device: Optional[str] = None) -> None: """ Recording thread. It reads raw frames from the audio device and dispatches them to ``detection_thread``. :param block_duration: Audio blocks duration. Specify either ``block_duration`` or ``block_size``. :param block_size: Size of the audio blocks. Specify either ``block_duration`` or ``block_size``. :param input_device: Input device """ assert (block_duration or block_size) and not (block_duration and block_size), \ 'Please specify either block_duration or block_size' if not block_size: block_size = int(self.rate * self.channels * block_duration) self.before_recording() self.logger.debug('Recording thread started') device = self._get_input_device(input_device) self._input_stream = sd.InputStream(samplerate=self.rate, device=device, channels=self.channels, dtype='int16', latency=0, blocksize=block_size) self._input_stream.start() self.on_recording_started() get_bus().post(SpeechDetectionStartedEvent()) while self._input_stream: try: frames = self._input_stream.read(block_size)[0] except Exception as e: self.logger.warning('Error while reading from the audio input: {}'.format(str(e))) continue self._audio_queue.put(frames) get_bus().post(SpeechDetectionStoppedEvent()) self.on_recording_ended() self.logger.debug('Recording thread terminated')
Example #4
Source File: rec_gui.py From python-sounddevice with MIT License | 5 votes |
def create_stream(self, device=None): if self.stream is not None: self.stream.close() self.stream = sd.InputStream( device=device, channels=1, callback=self.audio_callback) self.stream.start()
Example #5
Source File: asyncio_generators.py From python-sounddevice with MIT License | 5 votes |
def inputstream_generator(channels=1, **kwargs): """Generator that yields blocks of input data as NumPy arrays.""" q_in = asyncio.Queue() loop = asyncio.get_event_loop() def callback(indata, frame_count, time_info, status): loop.call_soon_threadsafe(q_in.put_nowait, (indata.copy(), status)) stream = sd.InputStream(callback=callback, channels=channels, **kwargs) with stream: while True: indata, status = await q_in.get() yield indata, status
Example #6
Source File: controller.py From AndroidMediaControlsWindows with GNU General Public License v3.0 | 4 votes |
def __init__(self): self.stream = sd.InputStream( samplerate=SAMPLE_RATE, blocksize=BLOCK_SIZE, channels=1, callback=self.process_frames ) self.stream.start() self.is_held = True self.times_pressed = 0
Example #7
Source File: TestSoundCard.py From urh with GNU General Public License v3.0 | 4 votes |
def test_sounddevice_lib(): import time import numpy as np from sounddevice import InputStream, OutputStream, sleep as sd_sleep """ if no portaudio installed: Traceback (most recent call last): File "TestSoundCard.py", line 42, in <module> test_sounddevice_lib() File "TestSoundCard.py", line 5, in test_sounddevice_lib import sounddevice as sd File "/usr/lib/python3.6/site-packages/sounddevice.py", line 64, in <module> raise OSError('PortAudio library not found') OSError: PortAudio library not found """ duration = 2.5 # seconds rx_buffer = np.ones((10 ** 6, 2), dtype=np.float32) global current_rx, current_tx current_rx = 0 current_tx = 0 def rx_callback(indata: np.ndarray, frames: int, time, status): global current_rx if status: print(status) rx_buffer[current_rx:current_rx + frames] = indata current_rx += frames def tx_callback(outdata: np.ndarray, frames: int, time, status): global current_tx if status: print(status) outdata[:] = rx_buffer[current_tx:current_tx + frames] current_tx += frames with InputStream(channels=2, callback=rx_callback): sd_sleep(int(duration * 1000)) print("Current rx", current_rx) with OutputStream(channels=2, callback=tx_callback): sd_sleep(int(duration * 1000)) print("Current tx", current_tx)