summaryrefslogtreecommitdiff
path: root/examples/asyncio_generators.py
diff options
context:
space:
mode:
authorMatthias Geier <Matthias.Geier@gmail.com>2019-01-14 13:12:16 +0100
committerMatthias Geier <Matthias.Geier@gmail.com>2019-02-09 16:30:33 +0100
commit53e001374aceb316de496234db4ce8e516491c6a (patch)
tree98d15b617bfd50cb9b63ae39d42b58ca2cc6c074 /examples/asyncio_generators.py
parent24c045a26080e5ba1fd7f6305e40b9eebf7f95ff (diff)
DOC: Add asyncio examples
Diffstat (limited to 'examples/asyncio_generators.py')
-rwxr-xr-xexamples/asyncio_generators.py104
1 files changed, 104 insertions, 0 deletions
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))