diff options
| author | Matthias Geier <Matthias.Geier@gmail.com> | 2019-01-14 13:12:16 +0100 |
|---|---|---|
| committer | Matthias Geier <Matthias.Geier@gmail.com> | 2019-02-09 16:30:33 +0100 |
| commit | 53e001374aceb316de496234db4ce8e516491c6a (patch) | |
| tree | 98d15b617bfd50cb9b63ae39d42b58ca2cc6c074 /examples | |
| parent | 24c045a26080e5ba1fd7f6305e40b9eebf7f95ff (diff) | |
DOC: Add asyncio examples
Diffstat (limited to 'examples')
| -rwxr-xr-x | examples/asyncio_coroutines.py | 73 | ||||
| -rwxr-xr-x | examples/asyncio_generators.py | 104 |
2 files changed, 177 insertions, 0 deletions
diff --git a/examples/asyncio_coroutines.py b/examples/asyncio_coroutines.py new file mode 100755 index 0000000..af6d707 --- /dev/null +++ b/examples/asyncio_coroutines.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""An example for using a stream in an asyncio coroutine. + +This example shows how to create a stream in a coroutine and how to wait for +the completion of the stream. + +You need Python 3.7 or newer to run this. + +""" +import asyncio + +import numpy as np +import sounddevice as sd + + +async 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() + + +async def play_buffer(buffer, **kwargs): + loop = asyncio.get_event_loop() + event = asyncio.Event() + idx = 0 + + def callback(outdata, 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 + valid_frames = frame_count if remainder >= frame_count else remainder + outdata[:valid_frames] = buffer[idx:idx + valid_frames] + outdata[valid_frames:] = 0 + idx += valid_frames + + stream = sd.OutputStream(callback=callback, dtype=buffer.dtype, + channels=buffer.shape[1], **kwargs) + with stream: + await event.wait() + + +async def main(frames=150_000, channels=1, dtype='float32', **kwargs): + buffer = np.empty((frames, channels), dtype=dtype) + print('recording buffer ...') + await record_buffer(buffer, **kwargs) + print('playing buffer ...') + await play_buffer(buffer, **kwargs) + print('done') + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/asyncio_generators.py b/examples/asyncio_generators.py new file mode 100755 index 0000000..c1e7bc6 --- /dev/null +++ b/examples/asyncio_generators.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Creating an asyncio generator for blocks of audio data. + +This example shows how a generator can be used to analyze audio input blocks. +In addition, it shows how a generator can be created that yields not only input +blocks but also output blocks where audio data can be written to. + +You need Python 3.7 or newer to run this. + +""" +import asyncio +import queue + +import numpy as np +import sounddevice as sd + + +async 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 + + +async def stream_generator(blocksize, *, channels=1, dtype='float32', + pre_fill_blocks=10, **kwargs): + """Generator that yields blocks of input/output data as NumPy arrays. + + The output blocks are uninitialized and have to be filled with + appropriate audio signals. + + """ + assert blocksize != 0 + q_in = asyncio.Queue() + q_out = queue.Queue() + loop = asyncio.get_event_loop() + + def callback(indata, outdata, frame_count, time_info, status): + loop.call_soon_threadsafe(q_in.put_nowait, (indata.copy(), status)) + outdata[:] = q_out.get_nowait() + + # pre-fill output queue + for _ in range(pre_fill_blocks): + q_out.put(np.zeros((blocksize, channels), dtype=dtype)) + + stream = sd.Stream(blocksize=blocksize, callback=callback, dtype=dtype, + channels=channels, **kwargs) + with stream: + while True: + indata, status = await q_in.get() + outdata = np.empty((blocksize, channels), dtype=dtype) + yield indata, outdata, status + q_out.put_nowait(outdata) + + +async def print_input_infos(**kwargs): + """Show minimum and maximum value of each incoming audio block.""" + async for indata, status in inputstream_generator(**kwargs): + if status: + print(status) + print('min:', indata.min(), '\t', 'max:', indata.max()) + + +async def wire_coro(**kwargs): + """Create a connection between audio inputs and outputs. + + Asynchronously iterates over a stream generator and for each block + simply copies the input data into the output block. + + """ + async for indata, outdata, status in stream_generator(**kwargs): + if status: + print(status) + outdata[:] = indata + + +async def main(**kwargs): + print('Some informations about the input signal:') + try: + await asyncio.wait_for(print_input_infos(), timeout=2) + except asyncio.TimeoutError: + pass + print('\nEnough of that, activating wire ...\n') + audio_task = asyncio.create_task(wire_coro(**kwargs)) + for i in range(10, 0, -1): + print(i) + await asyncio.sleep(1) + audio_task.cancel() + try: + await audio_task + except asyncio.CancelledError: + print('wire was cancelled') + + +if __name__ == "__main__": + asyncio.run(main(blocksize=1024)) |
