summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rwxr-xr-xexamples/play_file.py42
1 files changed, 36 insertions, 6 deletions
diff --git a/examples/play_file.py b/examples/play_file.py
index 8386027..2efefc7 100755
--- a/examples/play_file.py
+++ b/examples/play_file.py
@@ -1,15 +1,28 @@
#!/usr/bin/env python3
"""Load an audio file into memory and play its contents.
-NumPy and the soundfile module (https://PySoundFile.readthedocs.io/)
+NumPy and the soundfile module (https://python-soundfile.readthedocs.io/)
must be installed for this to work.
This example program loads the whole file into memory before starting
playback.
To play very long files, you should use play_long_file.py instead.
+This example could simply be implemented like this::
+
+ import sounddevice as sd
+ import soundfile as sf
+
+ data, fs = sf.read('my-file.wav')
+ sd.play(data, fs)
+ sd.wait()
+
+... but in this example we show a more low-level implementation
+using a callback stream.
+
"""
import argparse
+import threading
import sounddevice as sd
import soundfile as sf
@@ -43,13 +56,30 @@ parser.add_argument(
help='output device (numeric ID or substring)')
args = parser.parse_args(remaining)
+event = threading.Event()
+
try:
- data, fs = sf.read(args.filename, dtype='float32')
- sd.play(data, fs, device=args.device)
- status = sd.wait()
+ data, fs = sf.read(args.filename, always_2d=True)
+
+ current_frame = 0
+
+ def callback(outdata, frames, time, status):
+ global current_frame
+ if status:
+ print(status)
+ chunksize = min(len(data) - current_frame, frames)
+ outdata[:chunksize] = data[current_frame:current_frame + chunksize]
+ if chunksize < frames:
+ outdata[chunksize:] = 0
+ raise sd.CallbackStop()
+ current_frame += chunksize
+
+ stream = sd.OutputStream(
+ samplerate=fs, device=args.device, channels=data.shape[1],
+ callback=callback, finished_callback=event.set)
+ with stream:
+ event.wait() # Wait until playback is finished
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))