pyquist 0.2.5__tar.gz → 0.3.1__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.1}/PKG-INFO +30 -2
  2. {pyquist-0.2.5 → pyquist-0.3.1}/README.md +29 -1
  3. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/__init__.py +5 -1
  4. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/audio.py +38 -1
  5. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/audio_test.py +34 -0
  6. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/device.py +58 -41
  7. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/device_test.py +75 -69
  8. pyquist-0.3.1/pyquist/env.py +49 -0
  9. pyquist-0.3.1/pyquist/env_test.py +79 -0
  10. pyquist-0.3.1/pyquist/stream.py +213 -0
  11. pyquist-0.3.1/pyquist/stream_test.py +282 -0
  12. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/web/freesound.py +63 -31
  13. {pyquist-0.2.5 → pyquist-0.3.1/pyquist.egg-info}/PKG-INFO +30 -2
  14. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist.egg-info/SOURCES.txt +4 -0
  15. {pyquist-0.2.5 → pyquist-0.3.1}/LICENSE +0 -0
  16. {pyquist-0.2.5 → pyquist-0.3.1}/pyproject.toml +0 -0
  17. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/cli.py +0 -0
  18. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/helper.py +0 -0
  19. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/helper_test.py +0 -0
  20. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/paths.py +0 -0
  21. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/plot.py +0 -0
  22. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/plot_test.py +0 -0
  23. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/py.typed +0 -0
  24. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/score.py +0 -0
  25. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/score_test.py +0 -0
  26. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/test_data/232009__danmitch3ll__xylophone-sweep.wav +0 -0
  27. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/test_data/388954__fullmetaljedi__blues-riff-in-g-nylon.wav +0 -0
  28. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/test_data/434013__mrpearch__drum-patern.mp3 +0 -0
  29. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/test_data/ATTRIBUTION.md +0 -0
  30. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/test_data/ravel_bolero.mid +0 -0
  31. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/web/__init__.py +0 -0
  32. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist/web/theorytab.py +0 -0
  33. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist.egg-info/dependency_links.txt +0 -0
  34. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist.egg-info/entry_points.txt +0 -0
  35. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist.egg-info/requires.txt +0 -0
  36. {pyquist-0.2.5 → pyquist-0.3.1}/pyquist.egg-info/top_level.txt +0 -0
  37. {pyquist-0.2.5 → pyquist-0.3.1}/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.1
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.1"
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,43 @@ 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.
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.
90
+
91
+ Args:
92
+ kind: ``"input"`` or ``"output"`` to list only that kind; ``None``
93
+ (default) lists both.
90
94
  """
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"
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)
99
+
101
100
 
101
+ def has_audio_device(kind: str = "output") -> bool:
102
+ """Returns True if an audio device of this ``kind`` is available.
102
103
 
103
- def _in_browser() -> bool:
104
- """Returns True if running inside a browser-hosted Python runtime.
104
+ Use it to guard anything that needs a real sound card, like
105
+ :class:`~pyquist.Stream` or :func:`record`. It's False in a browser
106
+ (Pyodide / JupyterLite), on Google Colab, and on headless machines such
107
+ as CI runners, where querying the device raises instead.
105
108
 
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`.
109
+ Args:
110
+ kind: ``"input"`` or ``"output"`` (default).
111
111
  """
112
- return sys.platform == "emscripten"
112
+ if kind not in ("input", "output"):
113
+ raise ValueError(f"kind must be 'input' or 'output', got {kind!r}.")
114
+ if in_browser():
115
+ return False
116
+ try:
117
+ device = sd.query_devices(kind=kind)
118
+ except Exception:
119
+ return False
120
+ return device[f"max_{kind}_channels"] > 0
113
121
 
114
122
 
115
123
  def play(
@@ -128,8 +136,9 @@ def play(
128
136
 
129
137
  Args:
130
138
  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.
139
+ safe: If True (default), limits the peak amplitude to
140
+ :data:`SAFE_PEAK_DBFS` (-20 dBFS) before playback to protect ears
141
+ against accidentally hot signals.
133
142
  normalize: If True, normalizes the audio to 0 dBFS before playback.
134
143
  force_sounddevice: If True, always use sounddevice playback, even
135
144
  when called from a notebook. Useful when you want the audio
@@ -148,10 +157,10 @@ def play(
148
157
  if normalize:
149
158
  audio.normalize()
150
159
  audio.clip()
151
- if safe and audio.peak_amplitude > db_to_amplitude(_SAFE_PEAK_DBFS):
152
- audio.normalize(peak_dbfs=_SAFE_PEAK_DBFS)
160
+ if safe and audio.peak_amplitude > db_to_amplitude(SAFE_PEAK_DBFS):
161
+ audio.normalize(peak_dbfs=SAFE_PEAK_DBFS)
153
162
 
154
- if not force_sounddevice and _in_ipython_notebook():
163
+ if not force_sounddevice and in_ipython_notebook():
155
164
  # Imported lazily so headless / non-notebook usage doesn't need IPython.
156
165
  from IPython.display import Audio as IPythonAudio, display # type: ignore[import-not-found] # noqa: I001
157
166
 
@@ -184,7 +193,7 @@ def record(
184
193
  """
185
194
 
186
195
  # :mod:`sounddevice` is not available when running in browser, handle separately.
187
- if _in_browser():
196
+ if in_browser():
188
197
  return _record_in_browser(duration)
189
198
 
190
199
  device_info = sd.query_devices(sd.default.device[0])
@@ -292,16 +301,29 @@ def _prompt_device(kind: str, *, update_default: bool = False) -> Tuple[int, str
292
301
  the choice will be persisted (``update_default=True``) or applied for
293
302
  this session only.
294
303
  """
304
+ # Bail out cleanly if there are no devices of this kind — otherwise we'd
305
+ # print an empty listing and ask the user to pick anyway.
306
+ if not _print_devices(kind):
307
+ raise RuntimeError(f"No {kind} devices are available on this machine.")
308
+
309
+ label = f"default {kind}" if update_default else kind
310
+ choice = input(f"Select {label} device (ID or name): ").strip()
311
+ if choice.isdigit() or (choice.startswith("-") and choice[1:].isdigit()):
312
+ return _resolve_device(int(choice), kind)
313
+ return _resolve_device(choice, kind)
314
+
315
+
316
+ def _print_devices(kind: str) -> bool:
317
+ """Prints the devices of the given kind, returning False if there are none."""
295
318
  devices = sd.query_devices()
296
319
  slot = 0 if kind == "input" else 1
297
320
 
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
321
  eligible = [
301
322
  (i, dev) for i, dev in enumerate(devices) if dev[f"max_{kind}_channels"] > 0
302
323
  ]
303
324
  if not eligible:
304
- raise RuntimeError(f"No {kind} devices are available on this machine.")
325
+ print(f"No {kind} devices available.")
326
+ return False
305
327
 
306
328
  current_id = sd.default.device[slot]
307
329
 
@@ -323,12 +345,7 @@ def _prompt_device(kind: str, *, update_default: bool = False) -> Tuple[int, str
323
345
  tags.append("default")
324
346
  suffix = f" [{', '.join(tags)}]" if tags else ""
325
347
  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)
348
+ return True
332
349
 
333
350
 
334
351
  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,
@@ -571,5 +538,44 @@ class TestRecordDispatch(unittest.TestCase):
571
538
  mock_browser.assert_not_called()
572
539
 
573
540
 
541
+ class TestHasAudioDevice(unittest.TestCase):
542
+ def _query(self, **kwargs):
543
+ return mock.patch.object(device.sd, "query_devices", **kwargs)
544
+
545
+ def setUp(self):
546
+ p = mock.patch.object(device, "in_browser", return_value=False)
547
+ p.start()
548
+ self.addCleanup(p.stop)
549
+
550
+ def test_true_when_default_device_has_channels(self):
551
+ speakers = {
552
+ "name": "Speakers",
553
+ "max_input_channels": 0,
554
+ "max_output_channels": 2,
555
+ }
556
+ with self._query(return_value=speakers):
557
+ self.assertTrue(device.has_audio_device())
558
+ self.assertFalse(device.has_audio_device("input"))
559
+
560
+ def test_false_when_query_raises(self):
561
+ # Headless CI: PortAudio has no default device ("Error querying
562
+ # device -1").
563
+ error = device.sd.PortAudioError("Error querying device -1")
564
+ with self._query(side_effect=error):
565
+ self.assertFalse(device.has_audio_device())
566
+
567
+ def test_false_in_browser_without_querying(self):
568
+ with (
569
+ mock.patch.object(device, "in_browser", return_value=True),
570
+ self._query() as mock_query,
571
+ ):
572
+ self.assertFalse(device.has_audio_device())
573
+ mock_query.assert_not_called()
574
+
575
+ def test_rejects_bad_kind(self):
576
+ with self.assertRaises(ValueError):
577
+ device.has_audio_device("both")
578
+
579
+
574
580
  if __name__ == "__main__":
575
581
  unittest.main()
@@ -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