pyquist 0.2.5__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. {pyquist-0.2.5/pyquist.egg-info → pyquist-0.3.0}/PKG-INFO +30 -2
  2. {pyquist-0.2.5 → pyquist-0.3.0}/README.md +29 -1
  3. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/__init__.py +5 -1
  4. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/audio.py +38 -1
  5. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/audio_test.py +34 -0
  6. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/device.py +39 -44
  7. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/device_test.py +36 -69
  8. pyquist-0.3.0/pyquist/env.py +49 -0
  9. pyquist-0.3.0/pyquist/env_test.py +79 -0
  10. pyquist-0.3.0/pyquist/stream.py +213 -0
  11. pyquist-0.3.0/pyquist/stream_test.py +282 -0
  12. {pyquist-0.2.5 → pyquist-0.3.0/pyquist.egg-info}/PKG-INFO +30 -2
  13. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist.egg-info/SOURCES.txt +4 -0
  14. {pyquist-0.2.5 → pyquist-0.3.0}/LICENSE +0 -0
  15. {pyquist-0.2.5 → pyquist-0.3.0}/pyproject.toml +0 -0
  16. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/cli.py +0 -0
  17. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/helper.py +0 -0
  18. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/helper_test.py +0 -0
  19. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/paths.py +0 -0
  20. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/plot.py +0 -0
  21. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/plot_test.py +0 -0
  22. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/py.typed +0 -0
  23. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/score.py +0 -0
  24. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/score_test.py +0 -0
  25. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/test_data/232009__danmitch3ll__xylophone-sweep.wav +0 -0
  26. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/test_data/388954__fullmetaljedi__blues-riff-in-g-nylon.wav +0 -0
  27. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/test_data/434013__mrpearch__drum-patern.mp3 +0 -0
  28. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/test_data/ATTRIBUTION.md +0 -0
  29. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/test_data/ravel_bolero.mid +0 -0
  30. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/web/__init__.py +0 -0
  31. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/web/freesound.py +0 -0
  32. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist/web/theorytab.py +0 -0
  33. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist.egg-info/dependency_links.txt +0 -0
  34. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist.egg-info/entry_points.txt +0 -0
  35. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist.egg-info/requires.txt +0 -0
  36. {pyquist-0.2.5 → pyquist-0.3.0}/pyquist.egg-info/top_level.txt +0 -0
  37. {pyquist-0.2.5 → pyquist-0.3.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyquist
3
- Version: 0.2.5
3
+ Version: 0.3.0
4
4
  Summary: Barebones utilities for low-level computer music programming in Python and NumPy. Teaching library for CMU 15-322.
5
5
  Author: Chris Donahue
6
6
  License-Expression: MIT
@@ -100,7 +100,28 @@ score = Score([
100
100
  pq.play(score.render(sine_instrument, metronome=BasicMetronome(bpm=120)))
101
101
  ```
102
102
 
103
- For a guided walkthrough — visualization, MIDI parsing, scores, instruments — open [`examples/HelloPyquist.ipynb`](examples/HelloPyquist.ipynb) or [run it in Colab](https://colab.research.google.com/github/gclef-cmu/pyquist/blob/main/examples/HelloPyquist.ipynb).
103
+ Real-time audio with a `Stream`, which calls your function on each short block of audio as it plays. The callback fills `block` in place, at full scale: like `pq.play`, a stream is `safe=True` by default, which turns its output down to -20 dBFS.
104
+
105
+ ```python
106
+ import time
107
+
108
+ class Sine:
109
+ def __init__(self, frequency):
110
+ self.frequency = frequency
111
+ self.time = 0.0
112
+
113
+ def callback(self, block):
114
+ t = self.time + np.arange(len(block)) / block.sample_rate
115
+ block.samples[:, 0] = np.sin(2 * np.pi * self.frequency * t)
116
+ self.time += len(block) / block.sample_rate
117
+
118
+ with pq.Stream(Sine(440).callback):
119
+ time.sleep(2.0) # plays until the `with` block exits
120
+ ```
121
+
122
+ With input channels, `block` arrives holding the microphone signal, so a callback that does nothing is a passthrough (use headphones): `pq.Stream(lambda block: None, num_input_channels=1)`.
123
+
124
+ For a guided walkthrough — visualization, MIDI parsing, scores, instruments, a real-time piano — open [`examples/HelloPyquist.ipynb`](examples/HelloPyquist.ipynb) or [run it in Colab](https://colab.research.google.com/github/gclef-cmu/pyquist/blob/main/examples/HelloPyquist.ipynb).
104
125
 
105
126
  ## Installation
106
127
 
@@ -165,6 +186,13 @@ pyquist devices
165
186
  pyquist play test
166
187
  ```
167
188
 
189
+ Or, from Python, for the current session only:
190
+
191
+ ```python
192
+ pq.list_devices()
193
+ pq.set_output_device("Speakers") # device ID, or part of its name
194
+ ```
195
+
168
196
  ### Run notebooks
169
197
 
170
198
  ```sh
@@ -54,7 +54,28 @@ score = Score([
54
54
  pq.play(score.render(sine_instrument, metronome=BasicMetronome(bpm=120)))
55
55
  ```
56
56
 
57
- For a guided walkthrough — visualization, MIDI parsing, scores, instruments — open [`examples/HelloPyquist.ipynb`](examples/HelloPyquist.ipynb) or [run it in Colab](https://colab.research.google.com/github/gclef-cmu/pyquist/blob/main/examples/HelloPyquist.ipynb).
57
+ Real-time audio with a `Stream`, which calls your function on each short block of audio as it plays. The callback fills `block` in place, at full scale: like `pq.play`, a stream is `safe=True` by default, which turns its output down to -20 dBFS.
58
+
59
+ ```python
60
+ import time
61
+
62
+ class Sine:
63
+ def __init__(self, frequency):
64
+ self.frequency = frequency
65
+ self.time = 0.0
66
+
67
+ def callback(self, block):
68
+ t = self.time + np.arange(len(block)) / block.sample_rate
69
+ block.samples[:, 0] = np.sin(2 * np.pi * self.frequency * t)
70
+ self.time += len(block) / block.sample_rate
71
+
72
+ with pq.Stream(Sine(440).callback):
73
+ time.sleep(2.0) # plays until the `with` block exits
74
+ ```
75
+
76
+ With input channels, `block` arrives holding the microphone signal, so a callback that does nothing is a passthrough (use headphones): `pq.Stream(lambda block: None, num_input_channels=1)`.
77
+
78
+ For a guided walkthrough — visualization, MIDI parsing, scores, instruments, a real-time piano — open [`examples/HelloPyquist.ipynb`](examples/HelloPyquist.ipynb) or [run it in Colab](https://colab.research.google.com/github/gclef-cmu/pyquist/blob/main/examples/HelloPyquist.ipynb).
58
79
 
59
80
  ## Installation
60
81
 
@@ -119,6 +140,13 @@ pyquist devices
119
140
  pyquist play test
120
141
  ```
121
142
 
143
+ Or, from Python, for the current session only:
144
+
145
+ ```python
146
+ pq.list_devices()
147
+ pq.set_output_device("Speakers") # device ID, or part of its name
148
+ ```
149
+
122
150
  ### Run notebooks
123
151
 
124
152
  ```sh
@@ -1,7 +1,8 @@
1
- __version__ = "0.2.5"
1
+ __version__ = "0.3.0"
2
2
 
3
3
  from .audio import Audio
4
4
  from .device import (
5
+ list_devices,
5
6
  play,
6
7
  record,
7
8
  set_input_device,
@@ -15,6 +16,7 @@ from .score import (
15
16
  Metronome,
16
17
  Score,
17
18
  )
19
+ from .stream import Stream
18
20
 
19
21
  __all__ = [
20
22
  "__version__",
@@ -23,6 +25,7 @@ __all__ = [
23
25
  "Metronome",
24
26
  "Score",
25
27
  "Event",
28
+ "list_devices",
26
29
  "play",
27
30
  "plot",
28
31
  "plot_freq",
@@ -30,6 +33,7 @@ __all__ = [
30
33
  "record",
31
34
  "set_input_device",
32
35
  "set_output_device",
36
+ "Stream",
33
37
  ]
34
38
 
35
39
 
@@ -50,6 +50,15 @@ import soxr
50
50
 
51
51
  from .helper import db_to_amplitude
52
52
 
53
+ # Maximum channel count for the output formats people actually write from
54
+ # pyquist that impose a low one. Everything else (WAV, AIFF, OGG, CAF, ...) is
55
+ # left to libsndfile, which reports a channel count it can't handle with an
56
+ # opaque "Format not recognised." error.
57
+ _MAX_CHANNELS_BY_FORMAT = {
58
+ "MP3": 2,
59
+ "FLAC": 8,
60
+ }
61
+
53
62
 
54
63
  class Audio:
55
64
  """A wrapper around a 2D float32 numpy array of audio samples.
@@ -494,12 +503,40 @@ class Audio:
494
503
  ``[-1.0, 1.0]`` will clip in fixed-point formats; consider calling
495
504
  :meth:`clip` or :meth:`normalize` first.
496
505
 
497
- Raises ``ValueError`` if ``self.sample_rate`` is ``None``.
506
+ Raises ``ValueError`` if ``self.sample_rate`` is ``None``, or if the
507
+ target format cannot hold :attr:`num_channels` channels (``.mp3``
508
+ tops out at 2, ``.flac`` at 8); :meth:`as_mono` or a ``.wav``
509
+ destination gets around the latter.
498
510
  """
499
511
  if self._sample_rate is None:
500
512
  raise ValueError("Cannot write audio without a sample_rate.")
513
+ self._check_num_channels_writable(file, kwargs.get("format"))
501
514
  sf.write(file, self._samples, self._sample_rate, **kwargs)
502
515
 
516
+ def _check_num_channels_writable(self, file, format: Optional[str]) -> None:
517
+ """Raises ``ValueError`` if the target format can't hold our channels.
518
+
519
+ ``format`` is the explicit :func:`soundfile.write` keyword when the
520
+ caller passed one; otherwise the format is taken from the file
521
+ extension, the same way ``soundfile`` infers it. Unrecognized
522
+ formats are left alone — ``soundfile`` reports those itself.
523
+ """
524
+ if format is None:
525
+ name = getattr(file, "name", file)
526
+ if not isinstance(name, (str, pathlib.PurePath)):
527
+ return
528
+ format = pathlib.PurePath(name).suffix.lstrip(".")
529
+ format = format.upper()
530
+ max_channels = _MAX_CHANNELS_BY_FORMAT.get(format)
531
+ if max_channels is None or self.num_channels <= max_channels:
532
+ return
533
+ raise ValueError(
534
+ f"{format} supports at most {max_channels} "
535
+ f"channel{'' if max_channels == 1 else 's'}, but this audio has "
536
+ f"{self.num_channels}. Call .as_mono() first, or write to a "
537
+ f"format with no such limit (e.g. .wav)."
538
+ )
539
+
503
540
  # --- numpy interop ------------------------------------------------------
504
541
 
505
542
  def __array__(self, dtype=None, copy=None) -> np.ndarray:
@@ -1,4 +1,7 @@
1
+ import pathlib
2
+ import tempfile
1
3
  import unittest
4
+ from io import BytesIO
2
5
 
3
6
  import numpy as np
4
7
 
@@ -541,6 +544,37 @@ class TestAudio(unittest.TestCase):
541
544
  buffer[:] = 1.0
542
545
  self.assertTrue(np.all(backing == 1.0))
543
546
 
547
+ def test_write_channel_limits(self):
548
+ surround = Audio(np.zeros((100, 6), dtype=np.float32), sample_rate=44100)
549
+ stereo = Audio(np.zeros((100, 2), dtype=np.float32), sample_rate=44100)
550
+
551
+ with tempfile.TemporaryDirectory() as tmp:
552
+ tmp = pathlib.Path(tmp)
553
+
554
+ # mp3 tops out at 2 channels, flac at 8.
555
+ for path in (tmp / "out.mp3", tmp / "out.MP3"):
556
+ with self.assertRaises(ValueError) as ctx:
557
+ surround.write(path)
558
+ self.assertIn("MP3 supports at most 2 channels", str(ctx.exception))
559
+ self.assertIn("6", str(ctx.exception))
560
+ self.assertFalse(path.exists())
561
+ with self.assertRaises(ValueError):
562
+ Audio(np.zeros((100, 9), dtype=np.float32), sample_rate=44100).write(
563
+ tmp / "out.flac"
564
+ )
565
+
566
+ # Formats without a low limit, and channel counts within a limit,
567
+ # are unaffected.
568
+ surround.write(tmp / "out.wav")
569
+ self.assertEqual(Audio.from_file(tmp / "out.wav").num_channels, 6)
570
+ stereo.write(tmp / "out.mp3")
571
+ self.assertEqual(Audio.from_file(tmp / "out.mp3").num_channels, 2)
572
+
573
+ # File-like destinations are checked via the explicit format kwarg.
574
+ with self.assertRaises(ValueError):
575
+ surround.write(BytesIO(), format="MP3")
576
+ surround.write(BytesIO(), format="WAV")
577
+
544
578
 
545
579
  if __name__ == "__main__":
546
580
  unittest.main()
@@ -15,6 +15,7 @@ import sounddevice as sd
15
15
  import tqdm
16
16
 
17
17
  from .audio import Audio
18
+ from .env import in_browser, in_ipython_notebook
18
19
  from .helper import db_to_amplitude
19
20
  from .paths import CACHE_DIR
20
21
 
@@ -22,8 +23,8 @@ _DEFAULTS_PATH = CACHE_DIR / "device_defaults.json"
22
23
 
23
24
  DeviceRef = Union[int, str]
24
25
 
25
- # Peak ceiling applied by ``play(safe=True)``.
26
- _SAFE_PEAK_DBFS = -18.0
26
+ # Peak ceiling applied by ``play(safe=True)`` and ``Stream(safe=True)``.
27
+ SAFE_PEAK_DBFS = -20.0
27
28
 
28
29
 
29
30
  def set_input_device(
@@ -80,36 +81,21 @@ def set_output_device(
80
81
  _save_defaults(defaults)
81
82
 
82
83
 
83
- def _in_ipython_notebook() -> bool:
84
- """Returns True if running inside a notebook-style IPython kernel.
84
+ def list_devices(kind: Optional[str] = None) -> None:
85
+ """Prints the available audio devices.
85
86
 
86
- Anything that isn't plain Python or the IPython terminal REPL counts —
87
- this covers Jupyter (``ZMQInteractiveShell``), Google Colab
88
- (``google.colab._shell.Shell``), VSCode notebooks, and other kernel
89
- hosts where inline display is the right playback path.
90
- """
91
- try:
92
- from IPython import get_ipython # type: ignore[import-not-found]
93
- except ImportError:
94
- return False
95
- ipy = get_ipython()
96
- if ipy is None:
97
- return False
98
- # The only IPython context where inline display ISN'T the right answer
99
- # is the terminal REPL, which has its own audio output.
100
- return ipy.__class__.__name__ != "TerminalInteractiveShell"
101
-
102
-
103
- def _in_browser() -> bool:
104
- """Returns True if running inside a browser-hosted Python runtime.
87
+ Each device is listed with the ID to pass to :func:`set_input_device` /
88
+ :func:`set_output_device`, and tagged ``[current]`` if it is selected for
89
+ this session and ``[default]`` if it is the persisted default.
105
90
 
106
- Pyodide (and JupyterLite, which runs a Pyodide kernel) compiles
107
- CPython to WebAssembly via Emscripten, so ``sys.platform`` reports
108
- ``"emscripten"``. In these environments there is no OS audio device, so
109
- capture and playback must go through the Web Audio API rather than
110
- :mod:`sounddevice`.
91
+ Args:
92
+ kind: ``"input"`` or ``"output"`` to list only that kind; ``None``
93
+ (default) lists both.
111
94
  """
112
- return sys.platform == "emscripten"
95
+ if kind not in (None, "input", "output"):
96
+ raise ValueError(f"kind must be 'input', 'output', or None, got {kind!r}.")
97
+ for k in ("input", "output") if kind is None else (kind,):
98
+ _print_devices(k)
113
99
 
114
100
 
115
101
  def play(
@@ -128,8 +114,9 @@ def play(
128
114
 
129
115
  Args:
130
116
  audio: The audio to play. Must have a ``sample_rate``.
131
- safe: If True (default), limits the peak amplitude to -18 dBFS
132
- before playback to protect ears against accidentally hot signals.
117
+ safe: If True (default), limits the peak amplitude to
118
+ :data:`SAFE_PEAK_DBFS` (-20 dBFS) before playback to protect ears
119
+ against accidentally hot signals.
133
120
  normalize: If True, normalizes the audio to 0 dBFS before playback.
134
121
  force_sounddevice: If True, always use sounddevice playback, even
135
122
  when called from a notebook. Useful when you want the audio
@@ -148,10 +135,10 @@ def play(
148
135
  if normalize:
149
136
  audio.normalize()
150
137
  audio.clip()
151
- if safe and audio.peak_amplitude > db_to_amplitude(_SAFE_PEAK_DBFS):
152
- audio.normalize(peak_dbfs=_SAFE_PEAK_DBFS)
138
+ if safe and audio.peak_amplitude > db_to_amplitude(SAFE_PEAK_DBFS):
139
+ audio.normalize(peak_dbfs=SAFE_PEAK_DBFS)
153
140
 
154
- if not force_sounddevice and _in_ipython_notebook():
141
+ if not force_sounddevice and in_ipython_notebook():
155
142
  # Imported lazily so headless / non-notebook usage doesn't need IPython.
156
143
  from IPython.display import Audio as IPythonAudio, display # type: ignore[import-not-found] # noqa: I001
157
144
 
@@ -184,7 +171,7 @@ def record(
184
171
  """
185
172
 
186
173
  # :mod:`sounddevice` is not available when running in browser, handle separately.
187
- if _in_browser():
174
+ if in_browser():
188
175
  return _record_in_browser(duration)
189
176
 
190
177
  device_info = sd.query_devices(sd.default.device[0])
@@ -292,16 +279,29 @@ def _prompt_device(kind: str, *, update_default: bool = False) -> Tuple[int, str
292
279
  the choice will be persisted (``update_default=True``) or applied for
293
280
  this session only.
294
281
  """
282
+ # Bail out cleanly if there are no devices of this kind — otherwise we'd
283
+ # print an empty listing and ask the user to pick anyway.
284
+ if not _print_devices(kind):
285
+ raise RuntimeError(f"No {kind} devices are available on this machine.")
286
+
287
+ label = f"default {kind}" if update_default else kind
288
+ choice = input(f"Select {label} device (ID or name): ").strip()
289
+ if choice.isdigit() or (choice.startswith("-") and choice[1:].isdigit()):
290
+ return _resolve_device(int(choice), kind)
291
+ return _resolve_device(choice, kind)
292
+
293
+
294
+ def _print_devices(kind: str) -> bool:
295
+ """Prints the devices of the given kind, returning False if there are none."""
295
296
  devices = sd.query_devices()
296
297
  slot = 0 if kind == "input" else 1
297
298
 
298
- # Find devices that match the requested kind. Bail out cleanly if none —
299
- # otherwise we'd print an empty listing and ask the user to pick anyway.
300
299
  eligible = [
301
300
  (i, dev) for i, dev in enumerate(devices) if dev[f"max_{kind}_channels"] > 0
302
301
  ]
303
302
  if not eligible:
304
- raise RuntimeError(f"No {kind} devices are available on this machine.")
303
+ print(f"No {kind} devices available.")
304
+ return False
305
305
 
306
306
  current_id = sd.default.device[slot]
307
307
 
@@ -323,12 +323,7 @@ def _prompt_device(kind: str, *, update_default: bool = False) -> Tuple[int, str
323
323
  tags.append("default")
324
324
  suffix = f" [{', '.join(tags)}]" if tags else ""
325
325
  print(f" {i}: {dev['name']}{suffix}")
326
-
327
- label = f"default {kind}" if update_default else kind
328
- choice = input(f"Select {label} device (ID or name): ").strip()
329
- if choice.isdigit() or (choice.startswith("-") and choice[1:].isdigit()):
330
- return _resolve_device(int(choice), kind)
331
- return _resolve_device(choice, kind)
326
+ return True
332
327
 
333
328
 
334
329
  def _set_device_slot(slot: int, device_id: int) -> None:
@@ -194,6 +194,36 @@ class TestPromptDeviceAnnotations(unittest.TestCase):
194
194
  self.assertNotIn("[default]", out)
195
195
 
196
196
 
197
+ class TestListDevices(unittest.TestCase):
198
+ def setUp(self):
199
+ _patch_sd(self)
200
+
201
+ def _run(self, *args):
202
+ buf = io.StringIO()
203
+ with contextlib.redirect_stdout(buf):
204
+ device.list_devices(*args)
205
+ return buf.getvalue()
206
+
207
+ def test_lists_both_kinds(self):
208
+ out = self._run()
209
+ self.assertIn("Available input devices:", out)
210
+ self.assertIn("Available output devices:", out)
211
+ self.assertIn("1: MacBook Speakers", out)
212
+
213
+ def test_one_kind(self):
214
+ out = self._run("input")
215
+ self.assertIn("0: MacBook Microphone", out)
216
+ self.assertNotIn("MacBook Speakers", out)
217
+
218
+ def test_no_devices_of_kind(self):
219
+ _patch_sd(self, devices=[_FAKE_DEVICES[1]])
220
+ self.assertIn("No input devices", self._run("input"))
221
+
222
+ def test_invalid_kind(self):
223
+ with self.assertRaises(ValueError):
224
+ device.list_devices("in")
225
+
226
+
197
227
  class TestNoDevicesAvailable(unittest.TestCase):
198
228
  """Behavior when the machine has zero (or zero of one kind of) devices."""
199
229
 
@@ -421,7 +451,7 @@ class TestPlayDispatch(unittest.TestCase):
421
451
  def test_uses_sounddevice_outside_notebook(self):
422
452
  audio = self._make_audio()
423
453
  with (
424
- mock.patch.object(device, "_in_ipython_notebook", return_value=False),
454
+ mock.patch.object(device, "in_ipython_notebook", return_value=False),
425
455
  mock.patch.object(device.sd, "play") as mock_play,
426
456
  mock.patch.object(device.sd, "wait") as mock_wait,
427
457
  ):
@@ -438,7 +468,7 @@ class TestPlayDispatch(unittest.TestCase):
438
468
  fake_module.Audio = fake_audio_widget
439
469
  fake_module.display = fake_display
440
470
  with (
441
- mock.patch.object(device, "_in_ipython_notebook", return_value=True),
471
+ mock.patch.object(device, "in_ipython_notebook", return_value=True),
442
472
  mock.patch.dict("sys.modules", {"IPython.display": fake_module}),
443
473
  mock.patch.object(device.sd, "play") as mock_play,
444
474
  ):
@@ -454,7 +484,7 @@ class TestPlayDispatch(unittest.TestCase):
454
484
 
455
485
  audio = Audio(np.zeros(100, dtype=np.float32)) # no sample_rate
456
486
  with (
457
- mock.patch.object(device, "_in_ipython_notebook", return_value=False),
487
+ mock.patch.object(device, "in_ipython_notebook", return_value=False),
458
488
  mock.patch.object(device.sd, "play") as mock_play,
459
489
  ):
460
490
  with self.assertRaises(ValueError):
@@ -464,7 +494,7 @@ class TestPlayDispatch(unittest.TestCase):
464
494
  def test_force_sounddevice_overrides_notebook(self):
465
495
  audio = self._make_audio()
466
496
  with (
467
- mock.patch.object(device, "_in_ipython_notebook", return_value=True),
497
+ mock.patch.object(device, "in_ipython_notebook", return_value=True),
468
498
  mock.patch.object(device.sd, "play") as mock_play,
469
499
  mock.patch.object(device.sd, "wait"),
470
500
  ):
@@ -472,76 +502,13 @@ class TestPlayDispatch(unittest.TestCase):
472
502
  mock_play.assert_called_once()
473
503
 
474
504
 
475
- class TestInIPythonNotebook(unittest.TestCase):
476
- """``_in_ipython_notebook`` must recognise every flavour of notebook
477
- kernel — Jupyter, Colab, etc. — so that ``play`` doesn't fall through
478
- to a sounddevice call that would crash in browser-hosted environments
479
- with no audio device."""
480
-
481
- def _fake_ipython_module(self, shell_class_name: str):
482
- """Returns a fake ``IPython`` module whose ``get_ipython()`` yields a
483
- shell of the given class name."""
484
- # A real class (not MagicMock) is needed so .__class__.__name__ works.
485
- shell_cls = type(shell_class_name, (), {})
486
- fake_ipython = mock.MagicMock()
487
- fake_ipython.get_ipython.return_value = shell_cls()
488
- return fake_ipython
489
-
490
- def test_jupyter_kernel_detected(self):
491
- with mock.patch.dict(
492
- "sys.modules", {"IPython": self._fake_ipython_module("ZMQInteractiveShell")}
493
- ):
494
- self.assertTrue(device._in_ipython_notebook())
495
-
496
- def test_colab_kernel_detected(self):
497
- # Google Colab's shell is `google.colab._shell.Shell`. The class name
498
- # alone is enough to distinguish from the terminal REPL.
499
- with mock.patch.dict(
500
- "sys.modules", {"IPython": self._fake_ipython_module("Shell")}
501
- ):
502
- self.assertTrue(device._in_ipython_notebook())
503
-
504
- def test_terminal_repl_not_detected(self):
505
- with mock.patch.dict(
506
- "sys.modules",
507
- {"IPython": self._fake_ipython_module("TerminalInteractiveShell")},
508
- ):
509
- self.assertFalse(device._in_ipython_notebook())
510
-
511
- def test_no_active_kernel_not_detected(self):
512
- fake_ipython = mock.MagicMock()
513
- fake_ipython.get_ipython.return_value = None
514
- with mock.patch.dict("sys.modules", {"IPython": fake_ipython}):
515
- self.assertFalse(device._in_ipython_notebook())
516
-
517
- def test_no_ipython_installed_not_detected(self):
518
- # Simulate IPython being missing entirely.
519
- with mock.patch.dict("sys.modules", {"IPython": None}):
520
- self.assertFalse(device._in_ipython_notebook())
521
-
522
-
523
- class TestInBrowser(unittest.TestCase):
524
- """``_in_browser`` must recognise browser-hosted runtimes (Pyodide /
525
- JupyterLite) so that ``record`` delegates to the Web Audio backend instead
526
- of calling sounddevice, which would crash where there is no audio device."""
527
-
528
- def test_emscripten_platform_detected(self):
529
- with mock.patch.object(device.sys, "platform", "emscripten"):
530
- self.assertTrue(device._in_browser())
531
-
532
- def test_native_platform_not_detected(self):
533
- for platform_name in ("darwin", "linux", "win32"):
534
- with mock.patch.object(device.sys, "platform", platform_name):
535
- self.assertFalse(device._in_browser())
536
-
537
-
538
505
  class TestRecordDispatch(unittest.TestCase):
539
506
  """``record`` picks the right backend based on context."""
540
507
 
541
508
  def test_uses_browser_in_browser(self):
542
509
  sentinel = object()
543
510
  with (
544
- mock.patch.object(device, "_in_browser", return_value=True),
511
+ mock.patch.object(device, "in_browser", return_value=True),
545
512
  mock.patch.object(
546
513
  device, "_record_in_browser", return_value=sentinel
547
514
  ) as mock_browser,
@@ -554,7 +521,7 @@ class TestRecordDispatch(unittest.TestCase):
554
521
 
555
522
  def test_uses_sounddevice_outside_browser(self):
556
523
  with (
557
- mock.patch.object(device, "_in_browser", return_value=False),
524
+ mock.patch.object(device, "in_browser", return_value=False),
558
525
  mock.patch.object(device, "_record_in_browser") as mock_browser,
559
526
  mock.patch.object(
560
527
  device.sd,
@@ -0,0 +1,49 @@
1
+ """Detects the runtime environment pyquist is running in.
2
+
3
+ These checks decide how audio can reach the speakers: an inline player in a
4
+ notebook, the Web Audio API in a browser, or :mod:`sounddevice` otherwise.
5
+ """
6
+
7
+ import sys
8
+
9
+
10
+ def in_ipython_notebook() -> bool:
11
+ """Returns True if running inside a notebook-style IPython kernel.
12
+
13
+ Anything that isn't plain Python or the IPython terminal REPL counts —
14
+ this covers Jupyter (``ZMQInteractiveShell``), Google Colab
15
+ (``google.colab._shell.Shell``), VSCode notebooks, and other kernel
16
+ hosts where inline display is the right playback path.
17
+ """
18
+ try:
19
+ from IPython import get_ipython # type: ignore[import-not-found]
20
+ except ImportError:
21
+ return False
22
+ ipy = get_ipython()
23
+ if ipy is None:
24
+ return False
25
+ # The only IPython context where inline display ISN'T the right answer
26
+ # is the terminal REPL, which has its own audio output.
27
+ return ipy.__class__.__name__ != "TerminalInteractiveShell"
28
+
29
+
30
+ def in_browser() -> bool:
31
+ """Returns True if running inside a browser-hosted Python runtime.
32
+
33
+ Pyodide (and JupyterLite, which runs a Pyodide kernel) compiles
34
+ CPython to WebAssembly via Emscripten, so ``sys.platform`` reports
35
+ ``"emscripten"``. In these environments there is no OS audio device, so
36
+ capture and playback must go through the Web Audio API rather than
37
+ :mod:`sounddevice`.
38
+ """
39
+ return sys.platform == "emscripten"
40
+
41
+
42
+ def in_colab() -> bool:
43
+ """Returns True if running inside Google Colab.
44
+
45
+ Colab runs on a remote machine with no OS audio devices, so
46
+ :class:`~pyquist.Stream` and sounddevice playback are unavailable there.
47
+ Colab's kernel imports ``google.colab`` at startup.
48
+ """
49
+ return "google.colab" in sys.modules
@@ -0,0 +1,79 @@
1
+ import sys
2
+ import unittest
3
+ from unittest import mock
4
+
5
+ from . import env
6
+
7
+
8
+ class TestInColab(unittest.TestCase):
9
+ def test_true_when_google_colab_imported(self):
10
+ with mock.patch.dict("sys.modules", {"google.colab": mock.MagicMock()}):
11
+ self.assertTrue(env.in_colab())
12
+
13
+ def test_false_when_not_imported(self):
14
+ with mock.patch.dict("sys.modules"):
15
+ sys.modules.pop("google.colab", None)
16
+ self.assertFalse(env.in_colab())
17
+
18
+
19
+ class TestInIPythonNotebook(unittest.TestCase):
20
+ """``in_ipython_notebook`` must recognise every flavour of notebook
21
+ kernel — Jupyter, Colab, etc. — so that ``play`` doesn't fall through
22
+ to a sounddevice call that would crash in browser-hosted environments
23
+ with no audio env."""
24
+
25
+ def _fake_ipython_module(self, shell_class_name: str):
26
+ """Returns a fake ``IPython`` module whose ``get_ipython()`` yields a
27
+ shell of the given class name."""
28
+ # A real class (not MagicMock) is needed so .__class__.__name__ works.
29
+ shell_cls = type(shell_class_name, (), {})
30
+ fake_ipython = mock.MagicMock()
31
+ fake_ipython.get_ipython.return_value = shell_cls()
32
+ return fake_ipython
33
+
34
+ def test_jupyter_kernel_detected(self):
35
+ with mock.patch.dict(
36
+ "sys.modules", {"IPython": self._fake_ipython_module("ZMQInteractiveShell")}
37
+ ):
38
+ self.assertTrue(env.in_ipython_notebook())
39
+
40
+ def test_colab_kernel_detected(self):
41
+ # Google Colab's shell is `google.colab._shell.Shell`. The class name
42
+ # alone is enough to distinguish from the terminal REPL.
43
+ with mock.patch.dict(
44
+ "sys.modules", {"IPython": self._fake_ipython_module("Shell")}
45
+ ):
46
+ self.assertTrue(env.in_ipython_notebook())
47
+
48
+ def test_terminal_repl_not_detected(self):
49
+ with mock.patch.dict(
50
+ "sys.modules",
51
+ {"IPython": self._fake_ipython_module("TerminalInteractiveShell")},
52
+ ):
53
+ self.assertFalse(env.in_ipython_notebook())
54
+
55
+ def test_no_active_kernel_not_detected(self):
56
+ fake_ipython = mock.MagicMock()
57
+ fake_ipython.get_ipython.return_value = None
58
+ with mock.patch.dict("sys.modules", {"IPython": fake_ipython}):
59
+ self.assertFalse(env.in_ipython_notebook())
60
+
61
+ def test_no_ipython_installed_not_detected(self):
62
+ # Simulate IPython being missing entirely.
63
+ with mock.patch.dict("sys.modules", {"IPython": None}):
64
+ self.assertFalse(env.in_ipython_notebook())
65
+
66
+
67
+ class TestInBrowser(unittest.TestCase):
68
+ """``in_browser`` must recognise browser-hosted runtimes (Pyodide /
69
+ JupyterLite) so that ``record`` delegates to the Web Audio backend instead
70
+ of calling sounddevice, which would crash where there is no audio env."""
71
+
72
+ def test_emscripten_platform_detected(self):
73
+ with mock.patch.object(env.sys, "platform", "emscripten"):
74
+ self.assertTrue(env.in_browser())
75
+
76
+ def test_native_platform_not_detected(self):
77
+ for platform_name in ("darwin", "linux", "win32"):
78
+ with mock.patch.object(env.sys, "platform", platform_name):
79
+ self.assertFalse(env.in_browser())
@@ -0,0 +1,213 @@
1
+ """Real-time audio streaming via :mod:`sounddevice`.
2
+
3
+ A :class:`Stream` calls your function once per block of audio, while audio
4
+ is flowing to the speakers and/or from the microphone. The function gets a
5
+ single :class:`~pyquist.Audio` ``block`` that it modifies in place: on the
6
+ way in it holds the latest input (if any), and whatever it holds on the way
7
+ out is played::
8
+
9
+ import time
10
+
11
+ import numpy as np
12
+ import pyquist as pq
13
+
14
+ def noise(block: pq.Audio) -> None:
15
+ block.samples[:] = 0.1 * np.random.uniform(-1, 1, block.shape)
16
+
17
+ with pq.Stream(noise):
18
+ time.sleep(5.0)
19
+
20
+ Streams use the devices selected with :func:`~pyquist.set_input_device` /
21
+ :func:`~pyquist.set_output_device` (see :func:`~pyquist.list_devices`).
22
+ """
23
+
24
+ import signal
25
+ import threading
26
+ import traceback
27
+ from typing import Callable, Optional
28
+
29
+ import numpy as np
30
+ import sounddevice as sd
31
+
32
+ from .audio import Audio
33
+ from .device import SAFE_PEAK_DBFS
34
+ from .helper import db_to_amplitude
35
+
36
+
37
+ class Stream:
38
+ """A real-time audio stream that calls ``callback`` on each block.
39
+
40
+ Use it as a context manager (``with pq.Stream(callback): ...``), or call
41
+ :meth:`start` and :meth:`stop` yourself to keep it running across cells.
42
+
43
+ Each ``block`` holds ``block_size`` samples with
44
+ ``max(num_input_channels, num_output_channels)`` channels. It arrives
45
+ holding the input (zeros elsewhere), and its first ``num_output_channels``
46
+ channels are played once ``callback`` returns.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ callback: Callable[[Audio], None],
52
+ *,
53
+ num_input_channels: int = 0,
54
+ num_output_channels: int = 1,
55
+ block_size: int = 512,
56
+ sample_rate: int = 44100,
57
+ safe: bool = True,
58
+ ):
59
+ """Configures the stream; nothing plays until :meth:`start`.
60
+
61
+ Args:
62
+ callback: Called as ``callback(block)`` once per block, from the
63
+ audio thread. Must modify ``block`` in place, and return fast
64
+ enough to keep up (``block_size / sample_rate`` seconds).
65
+ num_input_channels: Channels to read from the input device; 0
66
+ (default) for no input.
67
+ num_output_channels: Channels to write to the output device; 0
68
+ for no output. Defaults to 1 (mono).
69
+ block_size: Samples per block. Smaller means lower latency but
70
+ more risk of glitches.
71
+ sample_rate: Sample rate in Hz.
72
+ safe: If True (default), multiplies every output block by a fixed
73
+ gain that maps full scale to ``SAFE_PEAK_DBFS`` (-20 dBFS), to
74
+ protect ears. Unlike :func:`~pyquist.play`, it never measures
75
+ or normalizes the signal, so the callback can write
76
+ full-scale ``[-1, 1]`` audio. False plays output unscaled.
77
+ """
78
+ if num_input_channels < 0 or num_output_channels < 0:
79
+ raise ValueError("Channel counts must be non-negative.")
80
+ if num_input_channels == 0 and num_output_channels == 0:
81
+ raise ValueError("Stream needs at least one input or output channel.")
82
+ self.callback = callback
83
+ self.num_input_channels = num_input_channels
84
+ self.num_output_channels = num_output_channels
85
+ self.block_size = block_size
86
+ self.sample_rate = sample_rate
87
+ self.safe = safe
88
+ self._buffer = Audio.empty(
89
+ block_size,
90
+ max(num_input_channels, num_output_channels),
91
+ sample_rate=sample_rate,
92
+ )
93
+ self._stream: Optional[sd.Stream | sd.InputStream | sd.OutputStream] = None
94
+ self._error: Optional[Exception] = None
95
+ # The main thread's ID while it runs a ``with`` block for this stream,
96
+ # so a callback error can interrupt it.
97
+ self._main_thread_id: Optional[int] = None
98
+ self._lock = threading.Lock()
99
+
100
+ def start(self) -> None:
101
+ """Opens the devices and starts calling ``callback``. No-op if running."""
102
+ if self._stream is not None:
103
+ return
104
+ num_in = _device_channels(self.num_input_channels, "input")
105
+ num_out = _device_channels(self.num_output_channels, "output")
106
+ kwargs = dict(
107
+ samplerate=self.sample_rate, blocksize=self.block_size, dtype="float32"
108
+ )
109
+ if num_in and num_out:
110
+ self._stream = sd.Stream(
111
+ channels=(num_in, num_out),
112
+ callback=lambda i, o, *_: self._process(i, o),
113
+ **kwargs,
114
+ )
115
+ elif num_in:
116
+ self._stream = sd.InputStream(
117
+ channels=num_in, callback=lambda i, *_: self._process(i, None), **kwargs
118
+ )
119
+ else:
120
+ self._stream = sd.OutputStream(
121
+ channels=num_out,
122
+ callback=lambda o, *_: self._process(None, o),
123
+ **kwargs,
124
+ )
125
+ self._stream.start()
126
+
127
+ def stop(self) -> None:
128
+ """Stops the stream. No-op if not running."""
129
+ if self._stream is not None:
130
+ self._stream.close()
131
+ self._stream = None
132
+
133
+ def __enter__(self) -> "Stream":
134
+ self.start()
135
+ if threading.current_thread() is threading.main_thread():
136
+ self._main_thread_id = threading.get_ident()
137
+ return self
138
+
139
+ def __exit__(self, *exc_info) -> None:
140
+ with self._lock:
141
+ self._main_thread_id = None
142
+ self.stop()
143
+ if self._error is not None:
144
+ # Replaces the KeyboardInterrupt that _report sent to get here.
145
+ error, self._error = self._error, None
146
+ raise error from None
147
+
148
+ def _process(
149
+ self, indata: Optional[np.ndarray], outdata: Optional[np.ndarray]
150
+ ) -> None:
151
+ """Runs one block: device input → ``callback`` → device output."""
152
+ try:
153
+ self._buffer.clear()
154
+ if indata is not None:
155
+ # Broadcasts a mono device across all input channels.
156
+ self._buffer.samples[:, : self.num_input_channels] = indata
157
+ self.callback(self._buffer)
158
+ if outdata is not None:
159
+ out = self._buffer.samples[:, : self.num_output_channels]
160
+ if outdata.shape[1] < out.shape[1]:
161
+ out = out.mean(axis=1, keepdims=True)
162
+ gain = db_to_amplitude(SAFE_PEAK_DBFS) if self.safe else 1.0
163
+ # Broadcasts mono output across a stereo device.
164
+ outdata[:] = gain * np.clip(out, -1.0, 1.0)
165
+ except Exception as e:
166
+ # Left alone, sounddevice would print this traceback and keep
167
+ # calling back, once per block. Report it, and abort.
168
+ self._report(e)
169
+ raise sd.CallbackAbort from e
170
+
171
+ def _report(self, error: Exception) -> None:
172
+ """Raises ``error`` in the ``with`` block if we can, or else prints it.
173
+
174
+ Exceptions can't cross threads, so we send the main thread a real
175
+ SIGINT, which interrupts even a blocking ``time.sleep`` (Python's
176
+ ``_thread.interrupt_main`` waits for the sleep to end). The resulting
177
+ KeyboardInterrupt unwinds the ``with`` block, and ``__exit__`` swaps
178
+ it for ``error``. We only do this while Python's default SIGINT handler
179
+ is installed, so it's never mistaken for an unrelated Ctrl+C handler.
180
+ """
181
+ with self._lock:
182
+ if (
183
+ self._main_thread_id is not None
184
+ and hasattr(signal, "pthread_kill") # Not on Windows.
185
+ and signal.getsignal(signal.SIGINT) is signal.default_int_handler
186
+ ):
187
+ thread_id, self._main_thread_id = self._main_thread_id, None
188
+ self._error = error
189
+ signal.pthread_kill(thread_id, signal.SIGINT)
190
+ return
191
+ traceback.print_exception(error)
192
+
193
+
194
+ def _device_channels(num_channels: int, kind: str) -> int:
195
+ """Returns how many channels to open on the current ``kind`` device.
196
+
197
+ Mono output opens two channels when it can, so it plays on both speakers.
198
+ Otherwise this is ``num_channels``, capped to what the device has — a cap
199
+ only allowed for mono devices, where :class:`Stream` duplicates or
200
+ averages to fit.
201
+ """
202
+ if num_channels == 0:
203
+ return 0
204
+ device = sd.query_devices(kind=kind)
205
+ available = device[f"max_{kind}_channels"]
206
+ if available == 0 or num_channels > available > 1:
207
+ raise ValueError(
208
+ f"Stream has {num_channels} {kind} channels, but {kind} device "
209
+ f"{device['name']!r} has {available}."
210
+ )
211
+ if kind == "output" and num_channels == 1:
212
+ return min(2, available)
213
+ return min(num_channels, available)
@@ -0,0 +1,282 @@
1
+ import contextlib
2
+ import io
3
+ import threading
4
+ import time
5
+ import unittest
6
+ from unittest import mock
7
+
8
+ import numpy as np
9
+
10
+ from . import stream
11
+ from .audio import Audio
12
+ from .device import SAFE_PEAK_DBFS
13
+ from .helper import db_to_amplitude
14
+ from .stream import Stream
15
+
16
+
17
+ class _FakeSdStream:
18
+ """Stand-in for the sounddevice stream classes; records how it was opened."""
19
+
20
+ def __init__(self, *, channels, callback, **kwargs):
21
+ self.channels = channels
22
+ self.callback = callback
23
+ self.kwargs = kwargs
24
+ self.started = self.closed = False
25
+
26
+ def start(self):
27
+ self.started = True
28
+
29
+ def close(self):
30
+ self.closed = True
31
+
32
+
33
+ def _patch_devices(test, *, num_in=2, num_out=2):
34
+ """Patches the current default devices to have the given channel counts."""
35
+
36
+ def query_devices(kind):
37
+ return {
38
+ "name": f"Fake {kind}",
39
+ "max_input_channels": num_in,
40
+ "max_output_channels": num_out,
41
+ }
42
+
43
+ for name, value in [
44
+ ("query_devices", query_devices),
45
+ ("Stream", _FakeSdStream),
46
+ ("InputStream", _FakeSdStream),
47
+ ("OutputStream", _FakeSdStream),
48
+ ]:
49
+ p = mock.patch.object(stream.sd, name, value)
50
+ p.start()
51
+ test.addCleanup(p.stop)
52
+
53
+
54
+ def _run_block(s: Stream, indata=None, num_out=None):
55
+ """Drives one callback through the stream's sounddevice callback."""
56
+ assert s._stream is not None
57
+ out = None if num_out is None else np.full((s.block_size, num_out), np.nan, "f4")
58
+ if indata is not None and out is not None:
59
+ s._stream.callback(indata, out, s.block_size, None, None)
60
+ elif indata is not None:
61
+ s._stream.callback(indata, s.block_size, None, None)
62
+ else:
63
+ s._stream.callback(out, s.block_size, None, None)
64
+ return out
65
+
66
+
67
+ class TestDeviceChannels(unittest.TestCase):
68
+ def test_matching(self):
69
+ _patch_devices(self, num_in=2, num_out=2)
70
+ self.assertEqual(stream._device_channels(2, "input"), 2)
71
+ self.assertEqual(stream._device_channels(2, "output"), 2)
72
+ self.assertEqual(stream._device_channels(0, "output"), 0)
73
+
74
+ def test_mono_output_opens_stereo(self):
75
+ _patch_devices(self, num_out=2)
76
+ self.assertEqual(stream._device_channels(1, "output"), 2)
77
+
78
+ def test_mono_input_from_stereo_device(self):
79
+ _patch_devices(self, num_in=2)
80
+ self.assertEqual(stream._device_channels(1, "input"), 1)
81
+
82
+ def test_mono_device(self):
83
+ _patch_devices(self, num_in=1, num_out=1)
84
+ self.assertEqual(stream._device_channels(2, "input"), 1)
85
+ self.assertEqual(stream._device_channels(2, "output"), 1)
86
+ self.assertEqual(stream._device_channels(1, "output"), 1)
87
+
88
+ def test_fewer_channels_than_device(self):
89
+ _patch_devices(self, num_out=8)
90
+ self.assertEqual(stream._device_channels(4, "output"), 4)
91
+
92
+ def test_too_many_channels(self):
93
+ _patch_devices(self, num_out=2)
94
+ with self.assertRaises(ValueError):
95
+ stream._device_channels(4, "output")
96
+
97
+ def test_no_channels(self):
98
+ _patch_devices(self, num_in=0)
99
+ with self.assertRaises(ValueError):
100
+ stream._device_channels(1, "input")
101
+
102
+
103
+ class TestStream(unittest.TestCase):
104
+ def test_invalid_channels(self):
105
+ with self.assertRaises(ValueError):
106
+ Stream(lambda block: None, num_output_channels=0)
107
+ with self.assertRaises(ValueError):
108
+ Stream(lambda block: None, num_input_channels=-1)
109
+
110
+ def test_context_manager_opens_and_closes(self):
111
+ _patch_devices(self)
112
+ s = Stream(lambda block: None, block_size=64, sample_rate=22050)
113
+ with s:
114
+ sd_stream = s._stream
115
+ self.assertTrue(sd_stream.started)
116
+ self.assertEqual(sd_stream.channels, 2)
117
+ self.assertEqual(sd_stream.kwargs["blocksize"], 64)
118
+ self.assertEqual(sd_stream.kwargs["samplerate"], 22050)
119
+ self.assertTrue(sd_stream.closed)
120
+ self.assertIsNone(s._stream)
121
+
122
+ def test_block_attributes(self):
123
+ _patch_devices(self)
124
+ seen = []
125
+ s = Stream(
126
+ seen.append, num_input_channels=1, num_output_channels=2, block_size=32
127
+ )
128
+ with s:
129
+ _run_block(s, indata=np.zeros((32, 1), "f4"), num_out=2)
130
+ (block,) = seen
131
+ self.assertIsInstance(block, Audio)
132
+ self.assertEqual(len(block), 32)
133
+ self.assertEqual(block.num_channels, 2)
134
+ self.assertEqual(block.sample_rate, 44100)
135
+
136
+ def test_mono_output_duplicated_and_clipped(self):
137
+ _patch_devices(self, num_out=2)
138
+
139
+ def callback(block):
140
+ block.samples[:] = np.linspace(-2, 2, len(block))[:, np.newaxis]
141
+
142
+ s = Stream(callback, block_size=16, safe=False)
143
+ with s:
144
+ out = _run_block(s, num_out=2)
145
+ expected = np.clip(np.linspace(-2, 2, 16), -1, 1)
146
+ np.testing.assert_allclose(out[:, 0], expected, rtol=1e-6)
147
+ np.testing.assert_array_equal(out[:, 0], out[:, 1])
148
+
149
+ def test_stereo_output_averaged_on_mono_device(self):
150
+ _patch_devices(self, num_out=1)
151
+
152
+ def callback(block):
153
+ block.samples[:, 0] = 0.5
154
+ block.samples[:, 1] = -0.1
155
+
156
+ s = Stream(callback, num_output_channels=2, block_size=16, safe=False)
157
+ with s:
158
+ out = _run_block(s, num_out=1)
159
+ np.testing.assert_allclose(out, 0.2, rtol=1e-6)
160
+
161
+ def test_passthrough(self):
162
+ _patch_devices(self)
163
+ s = Stream(
164
+ lambda block: None,
165
+ num_input_channels=2,
166
+ num_output_channels=2,
167
+ safe=False,
168
+ )
169
+ indata = np.random.uniform(-1, 1, (512, 2)).astype("f4")
170
+ with s:
171
+ out = _run_block(s, indata=indata, num_out=2)
172
+ np.testing.assert_array_equal(out, indata)
173
+
174
+ def test_mono_input_device_fills_all_channels(self):
175
+ _patch_devices(self, num_in=1)
176
+ seen = []
177
+ s = Stream(
178
+ lambda block: seen.append(block.copy()),
179
+ num_input_channels=2,
180
+ num_output_channels=0,
181
+ block_size=8,
182
+ )
183
+ with s:
184
+ _run_block(s, indata=np.ones((8, 1), "f4"))
185
+ np.testing.assert_array_equal(seen[0].samples, 1.0)
186
+
187
+ def test_extra_channels_start_silent(self):
188
+ _patch_devices(self)
189
+ seen = []
190
+ s = Stream(
191
+ lambda block: seen.append(block.copy()),
192
+ num_input_channels=1,
193
+ num_output_channels=2,
194
+ block_size=8,
195
+ )
196
+ with s:
197
+ _run_block(s, indata=np.ones((8, 1), "f4"), num_out=2)
198
+ _run_block(s, indata=np.ones((8, 1), "f4"), num_out=2)
199
+ for block in seen:
200
+ np.testing.assert_array_equal(block.samples[:, 0], 1.0)
201
+ np.testing.assert_array_equal(block.samples[:, 1], 0.0)
202
+
203
+ def test_safe_scales_full_scale_to_safe_peak(self):
204
+ _patch_devices(self, num_out=1)
205
+
206
+ def callback(block):
207
+ block.samples[:] = 1.0
208
+
209
+ s = Stream(callback, block_size=16)
210
+ with s:
211
+ out = _run_block(s, num_out=1)
212
+ np.testing.assert_allclose(out, db_to_amplitude(SAFE_PEAK_DBFS), rtol=1e-6)
213
+
214
+ def test_safe_does_not_change_block(self):
215
+ _patch_devices(self, num_out=1)
216
+ seen = []
217
+
218
+ def callback(block):
219
+ block.samples[:] = 0.5
220
+ seen.append(block)
221
+
222
+ s = Stream(callback, block_size=16)
223
+ with s:
224
+ _run_block(s, num_out=1)
225
+ np.testing.assert_array_equal(seen[0].samples, 0.5)
226
+
227
+ def _fail_from_audio_thread(self, s: Stream, delay=0.05):
228
+ """Runs a block on another thread, like sounddevice does, and returns
229
+ the exception that thread saw."""
230
+ seen = []
231
+
232
+ def run():
233
+ time.sleep(delay)
234
+ try:
235
+ _run_block(s, num_out=2)
236
+ except Exception as e:
237
+ seen.append(e)
238
+
239
+ thread = threading.Thread(target=run)
240
+ thread.start()
241
+ return thread, seen
242
+
243
+ def _failing_stream(self) -> Stream:
244
+ _patch_devices(self)
245
+
246
+ def callback(block):
247
+ raise RuntimeError("oops")
248
+
249
+ return Stream(callback)
250
+
251
+ def test_callback_error_interrupts_with_block(self):
252
+ s = self._failing_stream()
253
+ start = time.monotonic()
254
+ with self.assertRaisesRegex(RuntimeError, "oops"):
255
+ with s:
256
+ thread, seen = self._fail_from_audio_thread(s)
257
+ time.sleep(5.0)
258
+ thread.join()
259
+ self.assertLess(time.monotonic() - start, 2.0)
260
+ self.assertIsInstance(seen[0], stream.sd.CallbackAbort)
261
+ self.assertIsNone(s._stream)
262
+
263
+ def test_callback_error_printed_after_start(self):
264
+ s = self._failing_stream()
265
+ s.start()
266
+ stderr = io.StringIO()
267
+ with contextlib.redirect_stderr(stderr):
268
+ thread, seen = self._fail_from_audio_thread(s, delay=0.0)
269
+ thread.join()
270
+ self.assertIsInstance(seen[0], stream.sd.CallbackAbort)
271
+ self.assertIn("RuntimeError: oops", stderr.getvalue())
272
+ s.stop() # Already reported; doesn't raise again.
273
+
274
+ def test_ctrl_c_still_works(self):
275
+ _patch_devices(self)
276
+ with self.assertRaises(KeyboardInterrupt):
277
+ with Stream(lambda block: None):
278
+ raise KeyboardInterrupt
279
+
280
+
281
+ if __name__ == "__main__":
282
+ unittest.main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyquist
3
- Version: 0.2.5
3
+ Version: 0.3.0
4
4
  Summary: Barebones utilities for low-level computer music programming in Python and NumPy. Teaching library for CMU 15-322.
5
5
  Author: Chris Donahue
6
6
  License-Expression: MIT
@@ -100,7 +100,28 @@ score = Score([
100
100
  pq.play(score.render(sine_instrument, metronome=BasicMetronome(bpm=120)))
101
101
  ```
102
102
 
103
- For a guided walkthrough — visualization, MIDI parsing, scores, instruments — open [`examples/HelloPyquist.ipynb`](examples/HelloPyquist.ipynb) or [run it in Colab](https://colab.research.google.com/github/gclef-cmu/pyquist/blob/main/examples/HelloPyquist.ipynb).
103
+ Real-time audio with a `Stream`, which calls your function on each short block of audio as it plays. The callback fills `block` in place, at full scale: like `pq.play`, a stream is `safe=True` by default, which turns its output down to -20 dBFS.
104
+
105
+ ```python
106
+ import time
107
+
108
+ class Sine:
109
+ def __init__(self, frequency):
110
+ self.frequency = frequency
111
+ self.time = 0.0
112
+
113
+ def callback(self, block):
114
+ t = self.time + np.arange(len(block)) / block.sample_rate
115
+ block.samples[:, 0] = np.sin(2 * np.pi * self.frequency * t)
116
+ self.time += len(block) / block.sample_rate
117
+
118
+ with pq.Stream(Sine(440).callback):
119
+ time.sleep(2.0) # plays until the `with` block exits
120
+ ```
121
+
122
+ With input channels, `block` arrives holding the microphone signal, so a callback that does nothing is a passthrough (use headphones): `pq.Stream(lambda block: None, num_input_channels=1)`.
123
+
124
+ For a guided walkthrough — visualization, MIDI parsing, scores, instruments, a real-time piano — open [`examples/HelloPyquist.ipynb`](examples/HelloPyquist.ipynb) or [run it in Colab](https://colab.research.google.com/github/gclef-cmu/pyquist/blob/main/examples/HelloPyquist.ipynb).
104
125
 
105
126
  ## Installation
106
127
 
@@ -165,6 +186,13 @@ pyquist devices
165
186
  pyquist play test
166
187
  ```
167
188
 
189
+ Or, from Python, for the current session only:
190
+
191
+ ```python
192
+ pq.list_devices()
193
+ pq.set_output_device("Speakers") # device ID, or part of its name
194
+ ```
195
+
168
196
  ### Run notebooks
169
197
 
170
198
  ```sh
@@ -7,6 +7,8 @@ pyquist/audio_test.py
7
7
  pyquist/cli.py
8
8
  pyquist/device.py
9
9
  pyquist/device_test.py
10
+ pyquist/env.py
11
+ pyquist/env_test.py
10
12
  pyquist/helper.py
11
13
  pyquist/helper_test.py
12
14
  pyquist/paths.py
@@ -15,6 +17,8 @@ pyquist/plot_test.py
15
17
  pyquist/py.typed
16
18
  pyquist/score.py
17
19
  pyquist/score_test.py
20
+ pyquist/stream.py
21
+ pyquist/stream_test.py
18
22
  pyquist.egg-info/PKG-INFO
19
23
  pyquist.egg-info/SOURCES.txt
20
24
  pyquist.egg-info/dependency_links.txt
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes