diff options
| author | Matthias Geier <Matthias.Geier@gmail.com> | 2021-02-09 16:54:29 +0100 |
|---|---|---|
| committer | Matthias Geier <Matthias.Geier@gmail.com> | 2021-03-08 10:12:27 +0100 |
| commit | d353fbf6c751a7a91169c614df8f905f2c55821c (patch) | |
| tree | 57f457412594bef9f406044a6953f3121c28d802 /examples/play_file.py | |
| parent | b2a311d0256b214225109b0e27dd3bf02d4f1f75 (diff) | |
DOC: more low-level implementation of play_file.py example
Diffstat (limited to 'examples/play_file.py')
| -rwxr-xr-x | examples/play_file.py | 42 |
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)) |
