summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorMatthias Geier <Matthias.Geier@gmail.com>2019-09-17 20:12:20 +0200
committerMatthias Geier <Matthias.Geier@gmail.com>2019-09-18 13:10:33 +0200
commita82b9b56d44ed37c587648685826ad56b9177533 (patch)
treebd72d8becf6caaf2079cd4f31db42db4f7cba289 /examples
parente8253a615d6f70f7a1f6bc662e703a857fd2e8c4 (diff)
DOC: Update examples
Diffstat (limited to 'examples')
-rw-r--r--examples/README.rst11
-rwxr-xr-xexamples/asyncio_coroutines.py6
-rwxr-xr-xexamples/asyncio_generators.py10
-rwxr-xr-xexamples/play_file.py38
-rwxr-xr-xexamples/play_long_file.py51
-rwxr-xr-xexamples/play_sine.py33
-rwxr-xr-xexamples/plot_input.py31
-rwxr-xr-xexamples/rec_gui.py2
-rwxr-xr-xexamples/rec_unlimited.py52
-rwxr-xr-xexamples/spectrogram.py57
-rwxr-xr-xexamples/wire.py60
11 files changed, 223 insertions, 128 deletions
diff --git a/examples/README.rst b/examples/README.rst
new file mode 100644
index 0000000..1a26446
--- /dev/null
+++ b/examples/README.rst
@@ -0,0 +1,11 @@
+Example Programs
+================
+
+Most of these examples use the `argparse` module to handle command line
+arguments.
+To show a help text explaining all available arguments,
+use the ``--help`` argument.
+
+For example::
+
+ python3 play_file.py --help
diff --git a/examples/asyncio_coroutines.py b/examples/asyncio_coroutines.py
index af6d707..d31a1e3 100755
--- a/examples/asyncio_coroutines.py
+++ b/examples/asyncio_coroutines.py
@@ -8,6 +8,7 @@ You need Python 3.7 or newer to run this.
"""
import asyncio
+import sys
import numpy as np
import sounddevice as sd
@@ -70,4 +71,7 @@ async def main(frames=150_000, channels=1, dtype='float32', **kwargs):
if __name__ == "__main__":
- asyncio.run(main())
+ try:
+ asyncio.run(main())
+ except KeyboardInterrupt:
+ sys.exit('\nInterrupted by user')
diff --git a/examples/asyncio_generators.py b/examples/asyncio_generators.py
index c1e7bc6..463a650 100755
--- a/examples/asyncio_generators.py
+++ b/examples/asyncio_generators.py
@@ -10,6 +10,7 @@ You need Python 3.7 or newer to run this.
"""
import asyncio
import queue
+import sys
import numpy as np
import sounddevice as sd
@@ -36,7 +37,7 @@ async def stream_generator(blocksize, *, channels=1, dtype='float32',
The output blocks are uninitialized and have to be filled with
appropriate audio signals.
-
+
"""
assert blocksize != 0
q_in = asyncio.Queue()
@@ -97,8 +98,11 @@ async def main(**kwargs):
try:
await audio_task
except asyncio.CancelledError:
- print('wire was cancelled')
+ print('\nwire was cancelled')
if __name__ == "__main__":
- asyncio.run(main(blocksize=1024))
+ try:
+ asyncio.run(main(blocksize=1024))
+ except KeyboardInterrupt:
+ sys.exit('\nInterrupted by user')
diff --git a/examples/play_file.py b/examples/play_file.py
index c474a63..8386027 100755
--- a/examples/play_file.py
+++ b/examples/play_file.py
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""Load an audio file into memory and play its contents.
-NumPy and the soundfile module (http://PySoundFile.rtfd.io/) must be
-installed for this to work.
+NumPy and the soundfile module (https://PySoundFile.readthedocs.io/)
+must be installed for this to work.
This example program loads the whole file into memory before starting
playback.
@@ -11,6 +11,9 @@ To play very long files, you should use play_long_file.py instead.
"""
import argparse
+import sounddevice as sd
+import soundfile as sf
+
def int_or_str(text):
"""Helper function for argument parsing."""
@@ -19,21 +22,34 @@ def int_or_str(text):
except ValueError:
return text
-parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument('filename', help='audio file to be played back')
-parser.add_argument('-d', '--device', type=int_or_str,
- help='output device (numeric ID or substring)')
-args = parser.parse_args()
+
+parser = argparse.ArgumentParser(add_help=False)
+parser.add_argument(
+ '-l', '--list-devices', action='store_true',
+ help='show list of audio devices and exit')
+args, remaining = parser.parse_known_args()
+if args.list_devices:
+ print(sd.query_devices())
+ parser.exit(0)
+parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ parents=[parser])
+parser.add_argument(
+ 'filename', metavar='FILENAME',
+ help='audio file to be played back')
+parser.add_argument(
+ '-d', '--device', type=int_or_str,
+ help='output device (numeric ID or substring)')
+args = parser.parse_args(remaining)
try:
- import sounddevice as sd
- import soundfile as sf
data, fs = sf.read(args.filename, dtype='float32')
sd.play(data, fs, device=args.device)
status = sd.wait()
- if status:
- parser.exit('Error during playback: ' + str(status))
except KeyboardInterrupt:
parser.exit('\nInterrupted by user')
except Exception as e:
parser.exit(type(e).__name__ + ': ' + str(e))
+if status:
+ parser.exit('Error during playback: ' + str(status))
diff --git a/examples/play_long_file.py b/examples/play_long_file.py
index 90e41c9..e018fd9 100755
--- a/examples/play_long_file.py
+++ b/examples/play_long_file.py
@@ -1,24 +1,27 @@
#!/usr/bin/env python3
"""Play an audio file using a limited amount of memory.
-The soundfile module (http://PySoundFile.rtfd.io/) must be installed for
-this to work. NumPy is not needed.
+The soundfile module (https://PySoundFile.readthedocs.io/) must be
+installed for this to work. NumPy is not needed.
In contrast to play_file.py, which loads the whole file into memory
before starting playback, this example program only holds a given number
of audio blocks in memory and is therefore able to play files that are
larger than the available RAM.
+A similar example could of course be implemented using NumPy,
+but this example shows what can be done when NumPy is not available.
+
"""
-from __future__ import division, print_function
import argparse
-try:
- import queue # Python 3.x
-except ImportError:
- import Queue as queue # Python 2.x
+import queue
import sys
import threading
+import sounddevice as sd
+import soundfile as sf
+
+
def int_or_str(text):
"""Helper function for argument parsing."""
try:
@@ -26,16 +29,32 @@ def int_or_str(text):
except ValueError:
return text
-parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument('filename', help='audio file to be played back')
-parser.add_argument('-d', '--device', type=int_or_str,
- help='output device (numeric ID or substring)')
-parser.add_argument('-b', '--blocksize', type=int, default=2048,
- help='block size (default: %(default)s)')
+
+parser = argparse.ArgumentParser(add_help=False)
+parser.add_argument(
+ '-l', '--list-devices', action='store_true',
+ help='show list of audio devices and exit')
+args, remaining = parser.parse_known_args()
+if args.list_devices:
+ print(sd.query_devices())
+ parser.exit(0)
+parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ parents=[parser])
+parser.add_argument(
+ 'filename', metavar='FILENAME',
+ help='audio file to be played back')
+parser.add_argument(
+ '-d', '--device', type=int_or_str,
+ help='output device (numeric ID or substring)')
+parser.add_argument(
+ '-b', '--blocksize', type=int, default=2048,
+ help='block size (default: %(default)s)')
parser.add_argument(
'-q', '--buffersize', type=int, default=20,
help='number of blocks used for buffering (default: %(default)s)')
-args = parser.parse_args()
+args = parser.parse_args(remaining)
if args.blocksize == 0:
parser.error('blocksize must not be zero')
if args.buffersize < 1:
@@ -65,16 +84,12 @@ def callback(outdata, frames, time, status):
try:
- import sounddevice as sd
- import soundfile as sf
-
with sf.SoundFile(args.filename) as f:
for _ in range(args.buffersize):
data = f.buffer_read(args.blocksize, dtype='float32')
if not data:
break
q.put_nowait(data) # Pre-fill queue
-
stream = sd.RawOutputStream(
samplerate=f.samplerate, blocksize=args.blocksize,
device=args.device, channels=f.channels, dtype='float32',
diff --git a/examples/play_sine.py b/examples/play_sine.py
index 58027e6..de1875a 100755
--- a/examples/play_sine.py
+++ b/examples/play_sine.py
@@ -3,6 +3,9 @@
import argparse
import sys
+import numpy as np
+import sounddevice as sd
+
def int_or_str(text):
"""Helper function for argument parsing."""
@@ -12,31 +15,33 @@ def int_or_str(text):
return text
-parser = argparse.ArgumentParser(description=__doc__)
+parser = argparse.ArgumentParser(add_help=False)
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)')
+args, remaining = parser.parse_known_args()
+if args.list_devices:
+ print(sd.query_devices())
+ parser.exit(0)
+parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ parents=[parser])
parser.add_argument(
'frequency', nargs='?', metavar='FREQUENCY', type=float, default=500,
help='frequency in Hz (default: %(default)s)')
parser.add_argument(
+ '-d', '--device', type=int_or_str,
+ help='output device (numeric ID or substring)')
+parser.add_argument(
'-a', '--amplitude', type=float, default=0.2,
help='amplitude (default: %(default)s)')
-args = parser.parse_args()
+args = parser.parse_args(remaining)
-try:
- import numpy as np
- import sounddevice as sd
-
- if args.list_devices:
- print(sd.query_devices())
- parser.exit(0)
+start_idx = 0
+try:
samplerate = sd.query_devices(args.device, 'output')['default_samplerate']
- start_idx = 0
def callback(outdata, frames, time, status):
if status:
@@ -53,5 +58,7 @@ try:
print('press Return to quit')
print('#' * 80)
input()
+except KeyboardInterrupt:
+ parser.exit('')
except Exception as e:
parser.exit(type(e).__name__ + ': ' + str(e))
diff --git a/examples/plot_input.py b/examples/plot_input.py
index ad12a9c..cf325d6 100755
--- a/examples/plot_input.py
+++ b/examples/plot_input.py
@@ -8,6 +8,11 @@ import argparse
import queue
import sys
+from matplotlib.animation import FuncAnimation
+import matplotlib.pyplot as plt
+import numpy as np
+import sounddevice as sd
+
def int_or_str(text):
"""Helper function for argument parsing."""
@@ -17,10 +22,21 @@ def int_or_str(text):
return text
-parser = argparse.ArgumentParser(description=__doc__)
+parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
'-l', '--list-devices', action='store_true',
help='show list of audio devices and exit')
+args, remaining = parser.parse_known_args()
+if args.list_devices:
+ print(sd.query_devices())
+ parser.exit(0)
+parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ parents=[parser])
+parser.add_argument(
+ 'channels', type=int, default=[1], nargs='*', metavar='CHANNEL',
+ help='input channels to plot (default: the first)')
parser.add_argument(
'-d', '--device', type=int_or_str,
help='input device (numeric ID or substring)')
@@ -37,10 +53,7 @@ parser.add_argument(
parser.add_argument(
'-n', '--downsample', type=int, default=10, metavar='N',
help='display every Nth sample (default: %(default)s)')
-parser.add_argument(
- 'channels', type=int, default=[1], nargs='*', metavar='CHANNEL',
- help='input channels to plot (default: the first)')
-args = parser.parse_args()
+args = parser.parse_args(remaining)
if any(c < 1 for c in args.channels):
parser.error('argument CHANNEL: must be >= 1')
mapping = [c - 1 for c in args.channels] # Channel numbers start with 1
@@ -77,14 +90,6 @@ def update_plot(frame):
try:
- from matplotlib.animation import FuncAnimation
- import matplotlib.pyplot as plt
- import numpy as np
- import sounddevice as sd
-
- if args.list_devices:
- print(sd.query_devices())
- parser.exit(0)
if args.samplerate is None:
device_info = sd.query_devices(args.device, 'input')
args.samplerate = device_info['default_samplerate']
diff --git a/examples/rec_gui.py b/examples/rec_gui.py
index 71ebc62..f1528e7 100755
--- a/examples/rec_gui.py
+++ b/examples/rec_gui.py
@@ -82,7 +82,7 @@ class RecGui(tk.Tk):
stream = None
def __init__(self):
- tk.Tk.__init__(self)
+ super().__init__()
self.title('Recording GUI')
diff --git a/examples/rec_unlimited.py b/examples/rec_unlimited.py
index b69a3e2..ef15244 100755
--- a/examples/rec_unlimited.py
+++ b/examples/rec_unlimited.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Create a recording with arbitrary duration.
-PySoundFile (https://github.com/bastibe/PySoundFile/) has to be installed!
+The soundfile module (https://PySoundFile.readthedocs.io/) has to be installed!
"""
import argparse
@@ -9,6 +9,11 @@ import tempfile
import queue
import sys
+import sounddevice as sd
+import soundfile as sf
+import numpy # Make sure NumPy is loaded before it is used in the callback
+assert numpy # avoid "imported but unused" message (W0611)
+
def int_or_str(text):
"""Helper function for argument parsing."""
@@ -17,10 +22,22 @@ def int_or_str(text):
except ValueError:
return text
-parser = argparse.ArgumentParser(description=__doc__)
+
+parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
'-l', '--list-devices', action='store_true',
help='show list of audio devices and exit')
+args, remaining = parser.parse_known_args()
+if args.list_devices:
+ print(sd.query_devices())
+ parser.exit(0)
+parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ parents=[parser])
+parser.add_argument(
+ 'filename', nargs='?', metavar='FILENAME',
+ help='audio file to store recording to')
parser.add_argument(
'-d', '--device', type=int_or_str,
help='input device (numeric ID or substring)')
@@ -29,21 +46,20 @@ parser.add_argument(
parser.add_argument(
'-c', '--channels', type=int, default=1, help='number of input channels')
parser.add_argument(
- 'filename', nargs='?', metavar='FILENAME',
- help='audio file to store recording to')
-parser.add_argument(
'-t', '--subtype', type=str, help='sound file subtype (e.g. "PCM_24")')
-args = parser.parse_args()
+args = parser.parse_args(remaining)
-try:
- import sounddevice as sd
- import soundfile as sf
- import numpy # Make sure NumPy is loaded before it is used in the callback
- assert numpy # avoid "imported but unused" message (W0611)
+q = queue.Queue()
+
+
+def callback(indata, frames, time, status):
+ """This is called (from a separate thread) for each audio block."""
+ if status:
+ print(status, file=sys.stderr)
+ q.put(indata.copy())
- if args.list_devices:
- print(sd.query_devices())
- parser.exit(0)
+
+try:
if args.samplerate is None:
device_info = sd.query_devices(args.device, 'input')
# soundfile expects an int, sounddevice provides a float:
@@ -51,13 +67,6 @@ try:
if args.filename is None:
args.filename = tempfile.mktemp(prefix='delme_rec_unlimited_',
suffix='.wav', dir='')
- q = queue.Queue()
-
- def callback(indata, frames, time, status):
- """This is called (from a separate thread) for each audio block."""
- if status:
- print(status, file=sys.stderr)
- q.put(indata.copy())
# Make sure the file is opened before recording anything:
with sf.SoundFile(args.filename, mode='x', samplerate=args.samplerate,
@@ -69,7 +78,6 @@ try:
print('#' * 80)
while True:
file.write(q.get())
-
except KeyboardInterrupt:
print('\nRecording finished: ' + repr(args.filename))
parser.exit(0)
diff --git a/examples/spectrogram.py b/examples/spectrogram.py
index b28232b..c9ce94e 100755
--- a/examples/spectrogram.py
+++ b/examples/spectrogram.py
@@ -2,9 +2,11 @@
"""Show a text-mode spectrogram using live microphone data."""
import argparse
import math
-import numpy as np
import shutil
+import numpy as np
+import sounddevice as sd
+
usage_line = ' press <enter> to quit, +<enter> or -<enter> to change scaling '
@@ -15,28 +17,41 @@ def int_or_str(text):
except ValueError:
return text
+
try:
columns, _ = shutil.get_terminal_size()
except AttributeError:
columns = 80
-parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument('-l', '--list-devices', action='store_true',
- help='list audio devices and exit')
-parser.add_argument('-b', '--block-duration', type=float,
- metavar='DURATION', default=50,
- help='block size (default %(default)s milliseconds)')
-parser.add_argument('-c', '--columns', type=int, default=columns,
- help='width of spectrogram')
-parser.add_argument('-d', '--device', type=int_or_str,
- help='input device (numeric ID or substring)')
-parser.add_argument('-g', '--gain', type=float, default=10,
- help='initial gain factor (default %(default)s)')
-parser.add_argument('-r', '--range', type=float, nargs=2,
- metavar=('LOW', 'HIGH'), default=[100, 2000],
- help='frequency range (default %(default)s Hz)')
-args = parser.parse_args()
-
+parser = argparse.ArgumentParser(add_help=False)
+parser.add_argument(
+ '-l', '--list-devices', action='store_true',
+ help='show list of audio devices and exit')
+args, remaining = parser.parse_known_args()
+if args.list_devices:
+ print(sd.query_devices())
+ parser.exit(0)
+parser = argparse.ArgumentParser(
+ description=__doc__ + '\n\nSupported keys:' + usage_line,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ parents=[parser])
+parser.add_argument(
+ '-b', '--block-duration', type=float, metavar='DURATION', default=50,
+ help='block size (default %(default)s milliseconds)')
+parser.add_argument(
+ '-c', '--columns', type=int, default=columns,
+ help='width of spectrogram')
+parser.add_argument(
+ '-d', '--device', type=int_or_str,
+ help='input device (numeric ID or substring)')
+parser.add_argument(
+ '-g', '--gain', type=float, default=10,
+ help='initial gain factor (default %(default)s)')
+parser.add_argument(
+ '-r', '--range', type=float, nargs=2,
+ metavar=('LOW', 'HIGH'), default=[100, 2000],
+ help='frequency range (default %(default)s Hz)')
+args = parser.parse_args(remaining)
low, high = args.range
if high <= low:
parser.error('HIGH must be greater than LOW')
@@ -54,12 +69,6 @@ for bg, fg in zip(colors, colors[1:]):
gradient.append('\x1b[{};{}m{}'.format(fg, bg + 10, char))
try:
- import sounddevice as sd
-
- if args.list_devices:
- print(sd.query_devices())
- parser.exit(0)
-
samplerate = sd.query_devices(args.device, 'input')['default_samplerate']
delta_f = (high - low) / (args.columns - 1)
diff --git a/examples/wire.py b/examples/wire.py
index 32d6ebe..3ad189c 100755
--- a/examples/wire.py
+++ b/examples/wire.py
@@ -1,12 +1,16 @@
#!/usr/bin/env python3
"""Pass input directly to output.
-See https://www.assembla.com/spaces/portaudio/subversion/source/HEAD/portaudio/trunk/test/patest_wire.c
+https://app.assembla.com/spaces/portaudio/git/source/master/test/patest_wire.c
"""
import argparse
import logging
+import sounddevice as sd
+import numpy # Make sure NumPy is loaded before it is used in the callback
+assert numpy # avoid "imported but unused" message (W0611)
+
def int_or_str(text):
"""Helper function for argument parsing."""
@@ -16,29 +20,41 @@ def int_or_str(text):
return text
-parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument('-i', '--input-device', type=int_or_str,
- help='input device ID or substring')
-parser.add_argument('-o', '--output-device', type=int_or_str,
- help='output device ID or substring')
-parser.add_argument('-c', '--channels', type=int, default=2,
- help='number of channels')
-parser.add_argument('-t', '--dtype', help='audio data type')
-parser.add_argument('-s', '--samplerate', type=float, help='sampling rate')
-parser.add_argument('-b', '--blocksize', type=int, help='block size')
-parser.add_argument('-l', '--latency', type=float, help='latency in seconds')
-args = parser.parse_args()
+parser = argparse.ArgumentParser(add_help=False)
+parser.add_argument(
+ '-l', '--list-devices', action='store_true',
+ help='show list of audio devices and exit')
+args, remaining = parser.parse_known_args()
+if args.list_devices:
+ print(sd.query_devices())
+ parser.exit(0)
+parser = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ parents=[parser])
+parser.add_argument(
+ '-i', '--input-device', type=int_or_str,
+ help='input device (numeric ID or substring)')
+parser.add_argument(
+ '-o', '--output-device', type=int_or_str,
+ help='output device (numeric ID or substring)')
+parser.add_argument(
+ '-c', '--channels', type=int, default=2,
+ help='number of channels')
+parser.add_argument('--dtype', help='audio data type')
+parser.add_argument('--samplerate', type=float, help='sampling rate')
+parser.add_argument('--blocksize', type=int, help='block size')
+parser.add_argument('--latency', type=float, help='latency in seconds')
+args = parser.parse_args(remaining)
-try:
- import sounddevice as sd
- import numpy # Make sure NumPy is loaded before it is used in the callback
- assert numpy # avoid "imported but unused" message (W0611)
- def callback(indata, outdata, frames, time, status):
- if status:
- print(status)
- outdata[:] = indata
+def callback(indata, outdata, frames, time, status):
+ if status:
+ print(status)
+ outdata[:] = indata
+
+try:
with sd.Stream(device=(args.input_device, args.output_device),
samplerate=args.samplerate, blocksize=args.blocksize,
dtype=args.dtype, latency=args.latency,
@@ -48,6 +64,6 @@ try:
print('#' * 80)
input()
except KeyboardInterrupt:
- parser.exit('\nInterrupted by user')
+ parser.exit('')
except Exception as e:
parser.exit(type(e).__name__ + ': ' + str(e))