Skip to content

Commit 422d9e6

Browse files
committed
DOC: Add sine example
Closes #189.
1 parent 8b8e3bc commit 422d9e6

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

doc/examples.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@ Play a Very Long Sound File
1515

1616
.. literalinclude:: ../examples/play_long_file.py
1717

18+
Play a Sine Signal
19+
------------------
20+
21+
:download:`play_sine.py <../examples/play_sine.py>`
22+
23+
.. literalinclude:: ../examples/play_sine.py
24+
1825
Input to Output Pass-Through
1926
----------------------------
2027

examples/play_sine.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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

Comments
 (0)