pyquist 0.2.4__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.4/pyquist.egg-info → pyquist-0.3.0}/PKG-INFO +30 -2
  2. {pyquist-0.2.4 → pyquist-0.3.0}/README.md +29 -1
  3. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/__init__.py +5 -1
  4. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/audio.py +125 -72
  5. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/audio_test.py +34 -0
  6. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/device.py +46 -44
  7. {pyquist-0.2.4 → 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.4 → pyquist-0.3.0/pyquist.egg-info}/PKG-INFO +30 -2
  13. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist.egg-info/SOURCES.txt +4 -0
  14. {pyquist-0.2.4 → pyquist-0.3.0}/LICENSE +0 -0
  15. {pyquist-0.2.4 → pyquist-0.3.0}/pyproject.toml +0 -0
  16. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/cli.py +0 -0
  17. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/helper.py +0 -0
  18. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/helper_test.py +0 -0
  19. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/paths.py +0 -0
  20. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/plot.py +0 -0
  21. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/plot_test.py +0 -0
  22. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/py.typed +0 -0
  23. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/score.py +0 -0
  24. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/score_test.py +0 -0
  25. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/test_data/232009__danmitch3ll__xylophone-sweep.wav +0 -0
  26. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/test_data/388954__fullmetaljedi__blues-riff-in-g-nylon.wav +0 -0
  27. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/test_data/434013__mrpearch__drum-patern.mp3 +0 -0
  28. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/test_data/ATTRIBUTION.md +0 -0
  29. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/test_data/ravel_bolero.mid +0 -0
  30. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/web/__init__.py +0 -0
  31. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/web/freesound.py +0 -0
  32. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist/web/theorytab.py +0 -0
  33. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist.egg-info/dependency_links.txt +0 -0
  34. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist.egg-info/entry_points.txt +0 -0
  35. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist.egg-info/requires.txt +0 -0
  36. {pyquist-0.2.4 → pyquist-0.3.0}/pyquist.egg-info/top_level.txt +0 -0
  37. {pyquist-0.2.4 → 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.4
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.4"
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
 
@@ -25,12 +25,13 @@ in-place variants), all returning ``Audio``::
25
25
  mix = riff + drums[: len(riff)] # sum the overlapping region
26
26
  mix *= 0.5 # halve the amplitude in place
27
27
 
28
- On top of that it offers music-specific helpers that return new ``Audio``
29
- objects::
28
+ On top of that it offers music-specific helpers. Some derive a new ``Audio``
29
+ and leave the original alone; others (``normalize``, ``clip``, ``pan``) adjust
30
+ levels in place by default, with ``in_place=False`` to get a copy instead::
30
31
 
31
- clip = mix.as_mono().segment(offset=1.0, duration=3.0).resample(8000)
32
- clip.normalize(peak_dbfs=-1.0)
33
- clip.write("clip.wav")
32
+ excerpt = mix.as_mono().segment(offset=1.0, duration=3.0).resample(8000)
33
+ excerpt.normalize(peak_dbfs=-1.0) # in place
34
+ excerpt.write("excerpt.wav")
34
35
 
35
36
  See :meth:`Audio.zeros` for a silent destination buffer (or
36
37
  :meth:`Audio.empty` for an uninitialized one) and
@@ -49,6 +50,15 @@ import soxr
49
50
 
50
51
  from .helper import db_to_amplitude
51
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
+
52
62
 
53
63
  class Audio:
54
64
  """A wrapper around a 2D float32 numpy array of audio samples.
@@ -69,6 +79,8 @@ class Audio:
69
79
  >>> pq.play(audio)
70
80
  """
71
81
 
82
+ # --- Construction -------------------------------------------------------
83
+
72
84
  def __init__(
73
85
  self,
74
86
  samples: np.ndarray,
@@ -191,6 +203,15 @@ class Audio:
191
203
  samples = np.concatenate([a.samples for a in audios], axis=0)
192
204
  return cls(samples, sample_rate=sample_rates.pop())
193
205
 
206
+ def copy(self) -> "Audio":
207
+ """Returns a deep copy of this ``Audio``.
208
+
209
+ The returned ``Audio`` owns a fresh copy of the sample array, so
210
+ in-place mutations of either one leave the other untouched.
211
+ ``sample_rate`` is carried over.
212
+ """
213
+ return Audio(self._samples.copy(), sample_rate=self._sample_rate)
214
+
194
215
  # --- Core attributes ----------------------------------------------------
195
216
 
196
217
  @property
@@ -261,7 +282,7 @@ class Audio:
261
282
  raise ValueError(f"sample_rate must be positive, got {value}.")
262
283
  self._sample_rate = int(value)
263
284
 
264
- # --- Shape-derived properties ------------------------------------------
285
+ # --- Derived properties -------------------------------------------------
265
286
 
266
287
  @property
267
288
  def num_samples(self) -> int:
@@ -297,7 +318,7 @@ class Audio:
297
318
  return 0.0
298
319
  return float(np.abs(self._samples).max())
299
320
 
300
- # --- Mutation methods ---------------------------------------------------
321
+ # --- In-place methods ---------------------------------------------------
301
322
 
302
323
  def clear(self) -> None:
303
324
  """Fills the audio with silence (zeros) in place.
@@ -306,41 +327,6 @@ class Audio:
306
327
  """
307
328
  self._samples.fill(0.0)
308
329
 
309
- def segment(
310
- self,
311
- *,
312
- offset: Optional[float] = None,
313
- duration: Optional[float] = None,
314
- ) -> "Audio":
315
- """Returns a new ``Audio`` containing a time-slice of this one.
316
-
317
- Both ``offset`` and ``duration`` are in seconds and require
318
- ``sample_rate`` to be set. Out-of-range values are clamped: a negative
319
- ``offset`` is treated as zero, and a ``duration`` that runs past the
320
- end is truncated. With both arguments ``None`` this is a no-op that
321
- returns ``self``.
322
-
323
- Args:
324
- offset: Start time in seconds. Defaults to the beginning.
325
- duration: Length in seconds. Defaults to the rest of the audio.
326
-
327
- Returns:
328
- A new ``Audio`` carrying the same ``sample_rate`` as ``self``.
329
- """
330
- if offset is None and duration is None:
331
- return self
332
- if self._sample_rate is None:
333
- raise ValueError("segment() requires a sample_rate.")
334
- start = max(0, int((offset or 0.0) * self._sample_rate))
335
- end = (
336
- self.num_samples
337
- if duration is None
338
- else start + int(duration * self._sample_rate)
339
- )
340
- start = min(start, self.num_samples)
341
- end = max(start, min(end, self.num_samples))
342
- return Audio(self._samples[start:end, :], sample_rate=self._sample_rate)
343
-
344
330
  def normalize(self, *, peak_dbfs: float = 0.0, in_place: bool = True) -> "Audio":
345
331
  """Scales the audio so its peak amplitude matches ``peak_dbfs``.
346
332
 
@@ -384,35 +370,6 @@ class Audio:
384
370
  return self
385
371
  return Audio(clipped, sample_rate=self._sample_rate)
386
372
 
387
- def as_mono(self) -> "Audio":
388
- """Returns a mono (1-channel) version of the audio.
389
-
390
- Multi-channel audio is mixed down by averaging across channels
391
- (mean, not sum), which preserves perceived loudness without risking
392
- clipping. If the audio is already mono, returns ``self`` (no copy).
393
- """
394
- if self.num_channels == 1:
395
- return self
396
- mono = self._samples.mean(axis=1, keepdims=True).astype(np.float32)
397
- return Audio(mono, sample_rate=self._sample_rate)
398
-
399
- def as_stereo(self) -> "Audio":
400
- """Returns a stereo (2-channel) version of the audio.
401
-
402
- Mono audio is duplicated across both channels (the same signal in
403
- L and R). Stereo audio is returned as ``self`` (no copy). Audio with
404
- 3 or more channels raises ``ValueError`` — this method does not try
405
- to guess a downmix.
406
- """
407
- if self.num_channels == 2:
408
- return self
409
- if self.num_channels == 1:
410
- stereo = np.repeat(self._samples, 2, axis=1)
411
- return Audio(stereo, sample_rate=self._sample_rate)
412
- raise ValueError(
413
- f"Cannot convert audio with {self.num_channels} channels to stereo."
414
- )
415
-
416
373
  def pan(self, position: float = 0.0, *, in_place: bool = True) -> "Audio":
417
374
  """Pans stereo audio to ``position`` using an equal-power pan law.
418
375
 
@@ -446,6 +403,72 @@ class Audio:
446
403
  return self
447
404
  return Audio(self._samples * gains, sample_rate=self._sample_rate)
448
405
 
406
+ # --- Derived audio ------------------------------------------------------
407
+
408
+ def segment(
409
+ self,
410
+ *,
411
+ offset: Optional[float] = None,
412
+ duration: Optional[float] = None,
413
+ ) -> "Audio":
414
+ """Returns a new ``Audio`` containing a time-slice of this one.
415
+
416
+ Both ``offset`` and ``duration`` are in seconds and require
417
+ ``sample_rate`` to be set. Out-of-range values are clamped: a negative
418
+ ``offset`` is treated as zero, and a ``duration`` that runs past the
419
+ end is truncated. With both arguments ``None`` this is a no-op that
420
+ returns ``self``.
421
+
422
+ Args:
423
+ offset: Start time in seconds. Defaults to the beginning.
424
+ duration: Length in seconds. Defaults to the rest of the audio.
425
+
426
+ Returns:
427
+ A new ``Audio`` carrying the same ``sample_rate`` as ``self``.
428
+ """
429
+ if offset is None and duration is None:
430
+ return self
431
+ if self._sample_rate is None:
432
+ raise ValueError("segment() requires a sample_rate.")
433
+ start = max(0, int((offset or 0.0) * self._sample_rate))
434
+ end = (
435
+ self.num_samples
436
+ if duration is None
437
+ else start + int(duration * self._sample_rate)
438
+ )
439
+ start = min(start, self.num_samples)
440
+ end = max(start, min(end, self.num_samples))
441
+ return Audio(self._samples[start:end, :], sample_rate=self._sample_rate)
442
+
443
+ def as_mono(self) -> "Audio":
444
+ """Returns a mono (1-channel) version of the audio.
445
+
446
+ Multi-channel audio is mixed down by averaging across channels
447
+ (mean, not sum), which preserves perceived loudness without risking
448
+ clipping. If the audio is already mono, returns ``self`` (no copy).
449
+ """
450
+ if self.num_channels == 1:
451
+ return self
452
+ mono = self._samples.mean(axis=1, keepdims=True).astype(np.float32)
453
+ return Audio(mono, sample_rate=self._sample_rate)
454
+
455
+ def as_stereo(self) -> "Audio":
456
+ """Returns a stereo (2-channel) version of the audio.
457
+
458
+ Mono audio is duplicated across both channels (the same signal in
459
+ L and R). Stereo audio is returned as ``self`` (no copy). Audio with
460
+ 3 or more channels raises ``ValueError`` — this method does not try
461
+ to guess a downmix.
462
+ """
463
+ if self.num_channels == 2:
464
+ return self
465
+ if self.num_channels == 1:
466
+ stereo = np.repeat(self._samples, 2, axis=1)
467
+ return Audio(stereo, sample_rate=self._sample_rate)
468
+ raise ValueError(
469
+ f"Cannot convert audio with {self.num_channels} channels to stereo."
470
+ )
471
+
449
472
  def resample(self, new_sample_rate: int, **kwargs) -> "Audio":
450
473
  """Returns a new ``Audio`` resampled to ``new_sample_rate``.
451
474
 
@@ -469,6 +492,8 @@ class Audio:
469
492
  )
470
493
  return Audio(resampled, sample_rate=new_sample_rate)
471
494
 
495
+ # --- File I/O -----------------------------------------------------------
496
+
472
497
  def write(self, file: Union[str, IO], **kwargs) -> None:
473
498
  """Writes the audio to a file via ``soundfile``.
474
499
 
@@ -478,12 +503,40 @@ class Audio:
478
503
  ``[-1.0, 1.0]`` will clip in fixed-point formats; consider calling
479
504
  :meth:`clip` or :meth:`normalize` first.
480
505
 
481
- 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.
482
510
  """
483
511
  if self._sample_rate is None:
484
512
  raise ValueError("Cannot write audio without a sample_rate.")
513
+ self._check_num_channels_writable(file, kwargs.get("format"))
485
514
  sf.write(file, self._samples, self._sample_rate, **kwargs)
486
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
+
487
540
  # --- numpy interop ------------------------------------------------------
488
541
 
489
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,12 +15,17 @@ 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
19
+ from .helper import db_to_amplitude
18
20
  from .paths import CACHE_DIR
19
21
 
20
22
  _DEFAULTS_PATH = CACHE_DIR / "device_defaults.json"
21
23
 
22
24
  DeviceRef = Union[int, str]
23
25
 
26
+ # Peak ceiling applied by ``play(safe=True)`` and ``Stream(safe=True)``.
27
+ SAFE_PEAK_DBFS = -20.0
28
+
24
29
 
25
30
  def set_input_device(
26
31
  device_id_or_name: Optional[DeviceRef] = None,
@@ -76,36 +81,21 @@ def set_output_device(
76
81
  _save_defaults(defaults)
77
82
 
78
83
 
79
- def _in_ipython_notebook() -> bool:
80
- """Returns True if running inside a notebook-style IPython kernel.
81
-
82
- Anything that isn't plain Python or the IPython terminal REPL counts —
83
- this covers Jupyter (``ZMQInteractiveShell``), Google Colab
84
- (``google.colab._shell.Shell``), VSCode notebooks, and other kernel
85
- hosts where inline display is the right playback path.
86
- """
87
- try:
88
- from IPython import get_ipython # type: ignore[import-not-found]
89
- except ImportError:
90
- return False
91
- ipy = get_ipython()
92
- if ipy is None:
93
- return False
94
- # The only IPython context where inline display ISN'T the right answer
95
- # is the terminal REPL, which has its own audio output.
96
- return ipy.__class__.__name__ != "TerminalInteractiveShell"
97
-
84
+ def list_devices(kind: Optional[str] = None) -> None:
85
+ """Prints the available audio devices.
98
86
 
99
- def _in_browser() -> bool:
100
- """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.
101
90
 
102
- Pyodide (and JupyterLite, which runs a Pyodide kernel) compiles
103
- CPython to WebAssembly via Emscripten, so ``sys.platform`` reports
104
- ``"emscripten"``. In these environments there is no OS audio device, so
105
- capture and playback must go through the Web Audio API rather than
106
- :mod:`sounddevice`.
91
+ Args:
92
+ kind: ``"input"`` or ``"output"`` to list only that kind; ``None``
93
+ (default) lists both.
107
94
  """
108
- 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)
109
99
 
110
100
 
111
101
  def play(
@@ -124,8 +114,9 @@ def play(
124
114
 
125
115
  Args:
126
116
  audio: The audio to play. Must have a ``sample_rate``.
127
- safe: If True (default), attenuates the audio to -18 dBFS before
128
- 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.
129
120
  normalize: If True, normalizes the audio to 0 dBFS before playback.
130
121
  force_sounddevice: If True, always use sounddevice playback, even
131
122
  when called from a notebook. Useful when you want the audio
@@ -138,13 +129,16 @@ def play(
138
129
  if audio.sample_rate is None:
139
130
  raise ValueError("sample_rate is None; cannot play audio.")
140
131
 
132
+ # Copy up front so the caller's Audio is never touched, then do every
133
+ # level adjustment in place on that copy.
134
+ audio = audio.copy()
141
135
  if normalize:
142
- audio = audio.normalize(in_place=False)
143
- audio = audio.clip(in_place=False)
144
- if safe:
145
- audio = audio.normalize(peak_dbfs=-18.0, in_place=False)
136
+ audio.normalize()
137
+ audio.clip()
138
+ if safe and audio.peak_amplitude > db_to_amplitude(SAFE_PEAK_DBFS):
139
+ audio.normalize(peak_dbfs=SAFE_PEAK_DBFS)
146
140
 
147
- if not force_sounddevice and _in_ipython_notebook():
141
+ if not force_sounddevice and in_ipython_notebook():
148
142
  # Imported lazily so headless / non-notebook usage doesn't need IPython.
149
143
  from IPython.display import Audio as IPythonAudio, display # type: ignore[import-not-found] # noqa: I001
150
144
 
@@ -177,7 +171,7 @@ def record(
177
171
  """
178
172
 
179
173
  # :mod:`sounddevice` is not available when running in browser, handle separately.
180
- if _in_browser():
174
+ if in_browser():
181
175
  return _record_in_browser(duration)
182
176
 
183
177
  device_info = sd.query_devices(sd.default.device[0])
@@ -285,16 +279,29 @@ def _prompt_device(kind: str, *, update_default: bool = False) -> Tuple[int, str
285
279
  the choice will be persisted (``update_default=True``) or applied for
286
280
  this session only.
287
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."""
288
296
  devices = sd.query_devices()
289
297
  slot = 0 if kind == "input" else 1
290
298
 
291
- # Find devices that match the requested kind. Bail out cleanly if none —
292
- # otherwise we'd print an empty listing and ask the user to pick anyway.
293
299
  eligible = [
294
300
  (i, dev) for i, dev in enumerate(devices) if dev[f"max_{kind}_channels"] > 0
295
301
  ]
296
302
  if not eligible:
297
- raise RuntimeError(f"No {kind} devices are available on this machine.")
303
+ print(f"No {kind} devices available.")
304
+ return False
298
305
 
299
306
  current_id = sd.default.device[slot]
300
307
 
@@ -316,12 +323,7 @@ def _prompt_device(kind: str, *, update_default: bool = False) -> Tuple[int, str
316
323
  tags.append("default")
317
324
  suffix = f" [{', '.join(tags)}]" if tags else ""
318
325
  print(f" {i}: {dev['name']}{suffix}")
319
-
320
- label = f"default {kind}" if update_default else kind
321
- choice = input(f"Select {label} device (ID or name): ").strip()
322
- if choice.isdigit() or (choice.startswith("-") and choice[1:].isdigit()):
323
- return _resolve_device(int(choice), kind)
324
- return _resolve_device(choice, kind)
326
+ return True
325
327
 
326
328
 
327
329
  def _set_device_slot(slot: int, device_id: int) -> None: