|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Creating an asyncio generator for blocks of audio data. |
| 3 | +
|
| 4 | +This example shows how a generator can be used to analyze audio input blocks. |
| 5 | +In addition, it shows how a generator can be created that yields not only input |
| 6 | +blocks but also output blocks where audio data can be written to. |
| 7 | +
|
| 8 | +You need Python 3.7 or newer to run this. |
| 9 | +
|
| 10 | +""" |
| 11 | +import asyncio |
| 12 | +import queue |
| 13 | + |
| 14 | +import numpy as np |
| 15 | +import sounddevice as sd |
| 16 | + |
| 17 | + |
| 18 | +async def inputstream_generator(channels=1, **kwargs): |
| 19 | + """Generator that yields blocks of input data as NumPy arrays.""" |
| 20 | + q_in = asyncio.Queue() |
| 21 | + loop = asyncio.get_event_loop() |
| 22 | + |
| 23 | + def callback(indata, frame_count, time_info, status): |
| 24 | + loop.call_soon_threadsafe(q_in.put_nowait, (indata.copy(), status)) |
| 25 | + |
| 26 | + stream = sd.InputStream(callback=callback, channels=channels, **kwargs) |
| 27 | + with stream: |
| 28 | + while True: |
| 29 | + indata, status = await q_in.get() |
| 30 | + yield indata, status |
| 31 | + |
| 32 | + |
| 33 | +async def stream_generator(blocksize, *, channels=1, dtype='float32', |
| 34 | + pre_fill_blocks=10, **kwargs): |
| 35 | + """Generator that yields blocks of input/output data as NumPy arrays. |
| 36 | +
|
| 37 | + The output blocks are uninitialized and have to be filled with |
| 38 | + appropriate audio signals. |
| 39 | + |
| 40 | + """ |
| 41 | + assert blocksize != 0 |
| 42 | + q_in = asyncio.Queue() |
| 43 | + q_out = queue.Queue() |
| 44 | + loop = asyncio.get_event_loop() |
| 45 | + |
| 46 | + def callback(indata, outdata, frame_count, time_info, status): |
| 47 | + loop.call_soon_threadsafe(q_in.put_nowait, (indata.copy(), status)) |
| 48 | + outdata[:] = q_out.get_nowait() |
| 49 | + |
| 50 | + # pre-fill output queue |
| 51 | + for _ in range(pre_fill_blocks): |
| 52 | + q_out.put(np.zeros((blocksize, channels), dtype=dtype)) |
| 53 | + |
| 54 | + stream = sd.Stream(blocksize=blocksize, callback=callback, dtype=dtype, |
| 55 | + channels=channels, **kwargs) |
| 56 | + with stream: |
| 57 | + while True: |
| 58 | + indata, status = await q_in.get() |
| 59 | + outdata = np.empty((blocksize, channels), dtype=dtype) |
| 60 | + yield indata, outdata, status |
| 61 | + q_out.put_nowait(outdata) |
| 62 | + |
| 63 | + |
| 64 | +async def print_input_infos(**kwargs): |
| 65 | + """Show minimum and maximum value of each incoming audio block.""" |
| 66 | + async for indata, status in inputstream_generator(**kwargs): |
| 67 | + if status: |
| 68 | + print(status) |
| 69 | + print('min:', indata.min(), '\t', 'max:', indata.max()) |
| 70 | + |
| 71 | + |
| 72 | +async def wire_coro(**kwargs): |
| 73 | + """Create a connection between audio inputs and outputs. |
| 74 | +
|
| 75 | + Asynchronously iterates over a stream generator and for each block |
| 76 | + simply copies the input data into the output block. |
| 77 | +
|
| 78 | + """ |
| 79 | + async for indata, outdata, status in stream_generator(**kwargs): |
| 80 | + if status: |
| 81 | + print(status) |
| 82 | + outdata[:] = indata |
| 83 | + |
| 84 | + |
| 85 | +async def main(**kwargs): |
| 86 | + print('Some informations about the input signal:') |
| 87 | + try: |
| 88 | + await asyncio.wait_for(print_input_infos(), timeout=2) |
| 89 | + except asyncio.TimeoutError: |
| 90 | + pass |
| 91 | + print('\nEnough of that, activating wire ...\n') |
| 92 | + audio_task = asyncio.create_task(wire_coro(**kwargs)) |
| 93 | + for i in range(10, 0, -1): |
| 94 | + print(i) |
| 95 | + await asyncio.sleep(1) |
| 96 | + audio_task.cancel() |
| 97 | + try: |
| 98 | + await audio_task |
| 99 | + except asyncio.CancelledError: |
| 100 | + print('wire was cancelled') |
| 101 | + |
| 102 | + |
| 103 | +if __name__ == "__main__": |
| 104 | + asyncio.run(main(blocksize=1024)) |
0 commit comments