def __init__(self, channels, samplerate, **attrs): self._channels = channels self._stream = OutputStream(samplerate=samplerate, channels=channels, **attrs) self._stream.start()
def write(self, data): if not self.stream: self.stream = OutputStream(samplerate=self.sr, device=self.name, channels=1, blocksize=self.chunk_size, dtype='float32').__enter__() self.stream.write(data)
class OutputDevice(): def __init__(self, name, volume=100, sr=44100, chunk_size=1024): self.name = name self.volume = volume self.stream = None self.sr = sr self.chunk_size = chunk_size def write(self, data): if not self.stream: self.stream = OutputStream(samplerate=self.sr, device=self.name, channels=1, blocksize=self.chunk_size, dtype='float32').__enter__() self.stream.write(data)
def thread_target(): streams = [] for d in self.devices: streams.append(OutputStream(samplerate=self.sr, device=d, channels=1, blocksize=self.chunk_size, dtype='float32').__enter__()) try: while self.playing: print(streams) chunk = self.next_chunk() [s.write(chunk) for s in streams] except Exception as err: print('playing error') [s.__exit__() for s in streams] raise err
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)
class StreamWriter(base.Writer): """A :class:`~audiotsm.io.base.Writer` allowing to play the output of a :class:`~audiotsm.base.tsm.TSM` object directly. You should stop the :class:`~audiotsm.io.stream.StreamWriter` after using it with the :func:`~audiotsm.io.stream.StreamWriter.stop` method, or use it in a ``with`` statement as follow:: with WavWriter(2, 44100) as writer: # use writer... :param channels: the number of channels of the signal. :type channels: int :param samplerate: the sampling rate of the signal. :type samplerate: int :param attrs: additional parameters used to create the :class:`sounddevice.OutputStream` that is used by the :class:`~audiotsm.io.stream.StreamWriter`. """ def __init__(self, channels, samplerate, **attrs): self._channels = channels self._stream = OutputStream(samplerate=samplerate, channels=channels, **attrs) self._stream.start() @property def channels(self): return self._channels def write(self, buffer): if buffer.shape[0] != self.channels: raise ValueError("the buffer should have the same number of " "channels as the WavWriter") self._stream.write(np.ascontiguousarray(buffer.T)) return buffer.shape[1] def stop(self): """Stop the stream.""" self._stream.stop() def __enter__(self): return self def __exit__(self, _1, _2, _3): self.stop()
def run_server(self, room): try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) url = self.root.ids.server.text # create signaling and peer connection self.session = JanusSession(url) self.pc = RTCPeerConnection() self.pcs = {} # create media source video = VideoImageTrack(self) audio = AudioTrack(loop) # create media sink self.recorder = MediaStreamer(self.root.ids.network_camera) def out_cb(outdata: np.ndarray, frame_count, time_info, status): q_out = None for context in self.recorder.get_context(): try: if q_out is None: q_out = context.queue.get_nowait() else: q_out |= context.queue.get_nowait() except: pass if q_out is None: return if q_out.shape == outdata.shape: outdata[:] = q_out elif q_out.shape[0] * q_out.shape[1] == outdata.shape[ 0] * outdata.shape[1]: outdata[:] = q_out.reshape(outdata.shape) else: outdata[:] = np.zeros(outdata.shape, dtype=outdata.dtype) Logger.warning( f'Audio: wrong size, got {q_out.shape}, should {outdata.shape}' ) # run event loop try: out_stream = OutputStream( blocksize=1920, callback=out_cb, dtype='int16', channels=1, ) with out_stream, audio: loop.run_until_complete( self.__run( room=int(room), video=video, audio=audio, )) finally: # cleanup loop.run_until_complete(self.recorder.stop()) loop.run_until_complete(self.pc.close()) loop.run_until_complete(self.session.destroy()) for i in self.pcs: loop.run_until_complete(self.pcs[i].close()) self.pcs = {} pending = asyncio.Task.all_tasks(loop) for task in pending: task.cancel() # loop.run_until_complete(asyncio.gather(*pending, loop=loop)) loop.close() Logger.info('Loop: closed all') self._thread = None