|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Play a sine signal.""" |
| 3 | +import argparse |
| 4 | +import sys |
| 5 | + |
| 6 | + |
| 7 | +def int_or_str(text): |
| 8 | + """Helper function for argument parsing.""" |
| 9 | + try: |
| 10 | + return int(text) |
| 11 | + except ValueError: |
| 12 | + return text |
| 13 | + |
| 14 | + |
| 15 | +parser = argparse.ArgumentParser(description=__doc__) |
| 16 | +parser.add_argument( |
| 17 | + '-l', '--list-devices', action='store_true', |
| 18 | + help='show list of audio devices and exit') |
| 19 | +parser.add_argument( |
| 20 | + '-d', '--device', type=int_or_str, |
| 21 | + help='output device (numeric ID or substring)') |
| 22 | +parser.add_argument( |
| 23 | + 'frequency', nargs='?', metavar='FREQUENCY', type=float, default=500, |
| 24 | + help='frequency in Hz (default: %(default)s)') |
| 25 | +parser.add_argument( |
| 26 | + '-a', '--amplitude', type=float, default=0.2, |
| 27 | + help='amplitude (default: %(default)s)') |
| 28 | +args = parser.parse_args() |
| 29 | + |
| 30 | +try: |
| 31 | + import numpy as np |
| 32 | + import sounddevice as sd |
| 33 | + |
| 34 | + if args.list_devices: |
| 35 | + print(sd.query_devices()) |
| 36 | + parser.exit(0) |
| 37 | + |
| 38 | + samplerate = sd.query_devices(args.device, 'output')['default_samplerate'] |
| 39 | + start_idx = 0 |
| 40 | + |
| 41 | + def callback(outdata, frames, time, status): |
| 42 | + if status: |
| 43 | + print(status, file=sys.stderr) |
| 44 | + global start_idx |
| 45 | + t = (start_idx + np.arange(frames)) / samplerate |
| 46 | + t = t.reshape(-1, 1) |
| 47 | + outdata[:] = args.amplitude * np.sin(2 * np.pi * args.frequency * t) |
| 48 | + start_idx += frames |
| 49 | + |
| 50 | + with sd.OutputStream(device=args.device, channels=1, callback=callback, |
| 51 | + samplerate=samplerate): |
| 52 | + print('#' * 80) |
| 53 | + print('press Return to quit') |
| 54 | + print('#' * 80) |
| 55 | + input() |
| 56 | +except Exception as e: |
| 57 | + parser.exit(type(e).__name__ + ': ' + str(e)) |
0 commit comments