diff options
| author | Matthias Geier <Matthias.Geier@gmail.com> | 2019-07-28 12:51:36 +0200 |
|---|---|---|
| committer | Matthias Geier <Matthias.Geier@gmail.com> | 2019-07-28 12:51:36 +0200 |
| commit | 422d9e6111dd9ccc7754904213a734abd1bab740 (patch) | |
| tree | 33b514d02f9cf97b26f9483cd8abc4f9c247018d /examples | |
| parent | 8b8e3bce469e63f242b3fea20018bb23605df17a (diff) | |
DOC: Add sine example
Closes #189.
Diffstat (limited to 'examples')
| -rwxr-xr-x | examples/play_sine.py | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/examples/play_sine.py b/examples/play_sine.py new file mode 100755 index 0000000..58027e6 --- /dev/null +++ b/examples/play_sine.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Play a sine signal.""" +import argparse +import sys + + +def int_or_str(text): + """Helper function for argument parsing.""" + try: + return int(text) + except ValueError: + return text + + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument( + '-l', '--list-devices', action='store_true', + help='show list of audio devices and exit') +parser.add_argument( + '-d', '--device', type=int_or_str, + help='output device (numeric ID or substring)') +parser.add_argument( + 'frequency', nargs='?', metavar='FREQUENCY', type=float, default=500, + help='frequency in Hz (default: %(default)s)') +parser.add_argument( + '-a', '--amplitude', type=float, default=0.2, + help='amplitude (default: %(default)s)') +args = parser.parse_args() + +try: + import numpy as np + import sounddevice as sd + + if args.list_devices: + print(sd.query_devices()) + parser.exit(0) + + samplerate = sd.query_devices(args.device, 'output')['default_samplerate'] + start_idx = 0 + + def callback(outdata, frames, time, status): + if status: + print(status, file=sys.stderr) + global start_idx + t = (start_idx + np.arange(frames)) / samplerate + t = t.reshape(-1, 1) + outdata[:] = args.amplitude * np.sin(2 * np.pi * args.frequency * t) + start_idx += frames + + with sd.OutputStream(device=args.device, channels=1, callback=callback, + samplerate=samplerate): + print('#' * 80) + print('press Return to quit') + print('#' * 80) + input() +except Exception as e: + parser.exit(type(e).__name__ + ': ' + str(e)) |
