Skip to content

Commit d5511cb

Browse files
committed
Examples: Don't use the logging module, proper exit codes
1 parent b728182 commit d5511cb

6 files changed

Lines changed: 35 additions & 37 deletions

File tree

examples/play_file.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
1111
"""
1212
import argparse
13-
import logging
1413

1514

1615
def int_or_str(text):
@@ -33,7 +32,7 @@ def int_or_str(text):
3332
sd.play(data, fs, device=args.device, blocking=True)
3433
status = sd.get_status()
3534
if status:
36-
logging.warning(str(status))
35+
parser.exit('Error during playback: ' + str(status))
3736
except KeyboardInterrupt:
3837
parser.exit('\nInterrupted by user')
3938
except Exception as e:

examples/play_long_file.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@
1010
larger than the available RAM.
1111
1212
"""
13-
from __future__ import division
13+
from __future__ import division, print_function
1414
import argparse
1515
try:
1616
import queue # Python 3.x
1717
except ImportError:
1818
import Queue as queue # Python 2.x
19+
import sys
1920
import threading
2021

2122
def int_or_str(text):
@@ -47,12 +48,13 @@ def int_or_str(text):
4748
def callback(outdata, frames, time, status):
4849
assert frames == args.blocksize
4950
if status.output_underflow:
50-
parser.error('An output underflow occurred: increase blocksize?')
51+
print('Output underflow: increase blocksize?', file=sys.stderr)
5152
raise sd.CallbackAbort
53+
assert not status
5254
try:
5355
data = q.get_nowait()
5456
except queue.Empty:
55-
parser.error('Buffer is empty: increase buffersize?')
57+
print('Buffer is empty: increase buffersize?', file=sys.stderr)
5658
raise sd.CallbackAbort
5759
if len(data) < len(outdata):
5860
outdata[:len(data)] = data

examples/plot_input.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
#!/usr/bin/env python3
2-
"""Plot the live microphone signal(s) with matplotlib."""
2+
"""Plot the live microphone signal(s) with matplotlib.
3+
4+
Matplotlib and NumPy have to be installed.
5+
6+
"""
37
import argparse
4-
from queue import Queue, Empty
8+
import queue
9+
import sys
510

611

712
def int_or_str(text):
@@ -39,15 +44,15 @@ def int_or_str(text):
3944
if any(c < 1 for c in args.channels):
4045
parser.error('argument CHANNEL: must be >= 1')
4146
mapping = [c - 1 for c in args.channels] # Channel numbers start with 1
42-
queue = Queue()
47+
q = queue.Queue()
4348

4449

4550
def audio_callback(indata, frames, time, status):
4651
"""This is called (from a separate thread) for each audio block."""
4752
if status:
48-
print(status, flush=True)
53+
print(status, file=sys.stderr)
4954
# Fancy indexing with mapping creates a (necessary!) copy:
50-
queue.put(indata[::args.downsample, mapping])
55+
q.put(indata[::args.downsample, mapping])
5156

5257

5358
def update_plot(frame):
@@ -61,8 +66,8 @@ def update_plot(frame):
6166
block = True # The first read from the queue is blocking ...
6267
while True:
6368
try:
64-
data = queue.get(block=block)
65-
except Empty:
69+
data = q.get(block=block)
70+
except queue.Empty:
6671
break
6772
shift = len(data)
6873
plotdata = np.roll(plotdata, -shift, axis=0)
@@ -81,7 +86,7 @@ def update_plot(frame):
8186

8287
if args.list_devices:
8388
print(sd.query_devices())
84-
parser.exit()
89+
parser.exit(0)
8590
if args.samplerate is None:
8691
device_info = sd.query_devices(args.device, 'input')
8792
args.samplerate = device_info['default_samplerate']

examples/rec_unlimited.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,11 @@
33
44
PySoundFile (https://github.com/bastibe/PySoundFile/) has to be installed!
55
6-
WARNING: This works only in Python 3.x!
7-
86
"""
97
import argparse
108
import tempfile
11-
from queue import Queue
9+
import queue
10+
import sys
1211

1312

1413
def int_or_str(text):
@@ -42,21 +41,21 @@ def int_or_str(text):
4241

4342
if args.list_devices:
4443
print(sd.query_devices())
45-
parser.exit()
44+
parser.exit(0)
4645
if args.samplerate is None:
4746
device_info = sd.query_devices(args.device, 'input')
4847
# soundfile expects an int, sounddevice provides a float:
4948
args.samplerate = int(device_info['default_samplerate'])
5049
if args.filename is None:
5150
args.filename = tempfile.mktemp(prefix='rec_unlimited_',
5251
suffix='.wav', dir='')
53-
queue = Queue()
52+
q = queue.Queue()
5453

5554
def callback(indata, frames, time, status):
5655
"""This is called (from a separate thread) for each audio block."""
5756
if status:
58-
print(status, flush=True)
59-
queue.put(indata.copy())
57+
print(status, file=sys.stderr)
58+
q.put(indata.copy())
6059

6160
# Make sure the file is opened before recording anything:
6261
with sf.SoundFile(args.filename, mode='x', samplerate=args.samplerate,
@@ -67,9 +66,10 @@ def callback(indata, frames, time, status):
6766
print('press Ctrl+C to stop the recording')
6867
print('#' * 80)
6968
while True:
70-
file.write(queue.get())
69+
file.write(q.get())
7170

7271
except KeyboardInterrupt:
73-
parser.exit('\nRecording finished: ' + repr(args.filename))
72+
print('\nRecording finished: ' + repr(args.filename))
73+
parser.exit(0)
7474
except Exception as e:
7575
parser.exit(type(e).__name__ + ': ' + str(e))

examples/spectrogram.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env python3
22
"""Show a text-mode spectrogram using live microphone data."""
33
import argparse
4-
import logging
54
import math
65
import numpy as np
76
import shutil
@@ -59,19 +58,19 @@ def int_or_str(text):
5958

6059
if args.list_devices:
6160
print(sd.query_devices())
62-
parser.exit()
61+
parser.exit(0)
6362

6463
samplerate = sd.query_devices(args.device, 'input')['default_samplerate']
6564

6665
delta_f = (high - low) / (args.columns - 1)
6766
fftsize = math.ceil(samplerate / delta_f)
6867
low_bin = math.floor(low / delta_f)
6968

70-
cumulated_status = sd.CallbackFlags()
71-
7269
def callback(indata, frames, time, status):
73-
global cumulated_status
74-
cumulated_status |= status
70+
if status:
71+
text = ' ' + str(status) + ' '
72+
print('\x1b[34;40m', text.center(args.columns, '#'),
73+
'\x1b[0m', sep='', flush=True)
7574
if any(indata):
7675
magnitude = np.abs(np.fft.rfft(indata[:, 0], n=fftsize))
7776
magnitude *= args.gain / fftsize
@@ -97,8 +96,6 @@ def callback(indata, frames, time, status):
9796
print('\x1b[31;40m', usage_line.center(args.columns, '#'),
9897
'\x1b[0m', sep='', flush=True)
9998
break
100-
if cumulated_status:
101-
logging.warning(str(cumulated_status))
10299
except KeyboardInterrupt:
103100
parser.exit('Interrupted by user')
104101
except Exception as e:

examples/wire.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,9 @@ def int_or_str(text):
3131
try:
3232
import sounddevice as sd
3333

34-
cumulated_status = sd.CallbackFlags()
35-
3634
def callback(indata, outdata, frames, time, status):
37-
global cumulated_status
38-
cumulated_status |= status
35+
if status:
36+
print(status, flush=True)
3937
outdata[:] = indata
4038

4139
with sd.Stream(device=(args.input_device, args.output_device),
@@ -46,9 +44,6 @@ def callback(indata, outdata, frames, time, status):
4644
print('press Return to quit')
4745
print('#' * 80)
4846
input()
49-
50-
if cumulated_status:
51-
logging.warning(str(cumulated_status))
5247
except KeyboardInterrupt:
5348
parser.exit('\nInterrupted by user')
5449
except Exception as e:

0 commit comments

Comments
 (0)