pyquist 0.1.0__tar.gz → 0.2.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.
- {pyquist-0.1.0/pyquist.egg-info → pyquist-0.2.0}/PKG-INFO +13 -9
- {pyquist-0.1.0 → pyquist-0.2.0}/README.md +9 -7
- {pyquist-0.1.0 → pyquist-0.2.0}/pyproject.toml +4 -1
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/__init__.py +1 -1
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/audio.py +67 -6
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/audio_test.py +28 -1
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/device.py +53 -1
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/device_test.py +52 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/paths.py +1 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/score.py +115 -10
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/score_test.py +57 -7
- pyquist-0.2.0/pyquist/test_data/232009__danmitch3ll__xylophone-sweep.wav +0 -0
- pyquist-0.2.0/pyquist/test_data/ATTRIBUTION.md +17 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/web/theorytab.py +42 -13
- {pyquist-0.1.0 → pyquist-0.2.0/pyquist.egg-info}/PKG-INFO +13 -9
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist.egg-info/SOURCES.txt +2 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist.egg-info/requires.txt +4 -1
- {pyquist-0.1.0 → pyquist-0.2.0}/LICENSE +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/cli.py +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/helper.py +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/helper_test.py +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/plot.py +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/plot_test.py +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/py.typed +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/test_data/388954__fullmetaljedi__blues-riff-in-g-nylon.wav +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/test_data/434013__mrpearch__drum-patern.mp3 +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/test_data/ravel_bolero.mid +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/web/__init__.py +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist/web/freesound.py +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist.egg-info/dependency_links.txt +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist.egg-info/entry_points.txt +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/pyquist.egg-info/top_level.txt +0 -0
- {pyquist-0.1.0 → pyquist-0.2.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyquist
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.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
|
|
@@ -27,10 +27,12 @@ Requires-Dist: matplotlib
|
|
|
27
27
|
Requires-Dist: mido
|
|
28
28
|
Requires-Dist: numpy>=2.0
|
|
29
29
|
Requires-Dist: requests
|
|
30
|
-
Requires-Dist: resampy
|
|
31
30
|
Requires-Dist: sounddevice
|
|
32
31
|
Requires-Dist: soundfile
|
|
32
|
+
Requires-Dist: soxr
|
|
33
33
|
Requires-Dist: tqdm
|
|
34
|
+
Provides-Extra: browser
|
|
35
|
+
Requires-Dist: browseraudio>=0.3.0; extra == "browser"
|
|
34
36
|
Provides-Extra: dev
|
|
35
37
|
Requires-Dist: mypy>=1.13; extra == "dev"
|
|
36
38
|
Requires-Dist: pre-commit>=4.0; extra == "dev"
|
|
@@ -69,8 +71,10 @@ pq.plot_spec(audio) # spectrogram
|
|
|
69
71
|
Loading and transforming:
|
|
70
72
|
|
|
71
73
|
```python
|
|
72
|
-
|
|
73
|
-
|
|
74
|
+
from pyquist.paths import TEST_DATA_DIR
|
|
75
|
+
|
|
76
|
+
riff = pq.Audio.from_file(
|
|
77
|
+
TEST_DATA_DIR / "388954__fullmetaljedi__blues-riff-in-g-nylon.wav"
|
|
74
78
|
)
|
|
75
79
|
clip = riff.segment(offset=5.0, duration=3.0).resample(8000)
|
|
76
80
|
pq.play(clip)
|
|
@@ -79,7 +83,7 @@ pq.play(clip)
|
|
|
79
83
|
Rendering a `Score` with a custom instrument. An instrument is called as `instrument(**event.kwargs)` — declare the kwargs you use and absorb the rest with `**kwargs`:
|
|
80
84
|
|
|
81
85
|
```python
|
|
82
|
-
from pyquist.score import Score,
|
|
86
|
+
from pyquist.score import Score, BasicMetronome
|
|
83
87
|
from pyquist.helper import pitch_to_frequency
|
|
84
88
|
|
|
85
89
|
def sine_instrument(pitch, duration, **kwargs):
|
|
@@ -89,11 +93,11 @@ def sine_instrument(pitch, duration, **kwargs):
|
|
|
89
93
|
return pq.Audio(0.3 * np.sin(2 * np.pi * freq * t) * np.exp(-3 * t), sample_rate=sr)
|
|
90
94
|
|
|
91
95
|
score = Score([
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
96
|
+
(0, {"pitch": 60, "duration": 0.5}),
|
|
97
|
+
(1, {"pitch": 64, "duration": 0.5}),
|
|
98
|
+
(2, {"pitch": 67, "duration": 0.5}),
|
|
95
99
|
])
|
|
96
|
-
pq.play(score.render(sine_instrument, metronome=BasicMetronome(120)))
|
|
100
|
+
pq.play(score.render(sine_instrument, metronome=BasicMetronome(bpm=120)))
|
|
97
101
|
```
|
|
98
102
|
|
|
99
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).
|
|
@@ -25,8 +25,10 @@ pq.plot_spec(audio) # spectrogram
|
|
|
25
25
|
Loading and transforming:
|
|
26
26
|
|
|
27
27
|
```python
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
from pyquist.paths import TEST_DATA_DIR
|
|
29
|
+
|
|
30
|
+
riff = pq.Audio.from_file(
|
|
31
|
+
TEST_DATA_DIR / "388954__fullmetaljedi__blues-riff-in-g-nylon.wav"
|
|
30
32
|
)
|
|
31
33
|
clip = riff.segment(offset=5.0, duration=3.0).resample(8000)
|
|
32
34
|
pq.play(clip)
|
|
@@ -35,7 +37,7 @@ pq.play(clip)
|
|
|
35
37
|
Rendering a `Score` with a custom instrument. An instrument is called as `instrument(**event.kwargs)` — declare the kwargs you use and absorb the rest with `**kwargs`:
|
|
36
38
|
|
|
37
39
|
```python
|
|
38
|
-
from pyquist.score import Score,
|
|
40
|
+
from pyquist.score import Score, BasicMetronome
|
|
39
41
|
from pyquist.helper import pitch_to_frequency
|
|
40
42
|
|
|
41
43
|
def sine_instrument(pitch, duration, **kwargs):
|
|
@@ -45,11 +47,11 @@ def sine_instrument(pitch, duration, **kwargs):
|
|
|
45
47
|
return pq.Audio(0.3 * np.sin(2 * np.pi * freq * t) * np.exp(-3 * t), sample_rate=sr)
|
|
46
48
|
|
|
47
49
|
score = Score([
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
50
|
+
(0, {"pitch": 60, "duration": 0.5}),
|
|
51
|
+
(1, {"pitch": 64, "duration": 0.5}),
|
|
52
|
+
(2, {"pitch": 67, "duration": 0.5}),
|
|
51
53
|
])
|
|
52
|
-
pq.play(score.render(sine_instrument, metronome=BasicMetronome(120)))
|
|
54
|
+
pq.play(score.render(sine_instrument, metronome=BasicMetronome(bpm=120)))
|
|
53
55
|
```
|
|
54
56
|
|
|
55
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).
|
|
@@ -30,13 +30,16 @@ dependencies = [
|
|
|
30
30
|
"mido",
|
|
31
31
|
"numpy>=2.0",
|
|
32
32
|
"requests",
|
|
33
|
-
"resampy",
|
|
34
33
|
"sounddevice",
|
|
35
34
|
"soundfile",
|
|
35
|
+
"soxr",
|
|
36
36
|
"tqdm",
|
|
37
37
|
]
|
|
38
38
|
|
|
39
39
|
[project.optional-dependencies]
|
|
40
|
+
browser = [
|
|
41
|
+
"browseraudio>=0.3.0",
|
|
42
|
+
]
|
|
40
43
|
dev = [
|
|
41
44
|
"mypy>=1.13",
|
|
42
45
|
"pre-commit>=4.0",
|
|
@@ -1,11 +1,50 @@
|
|
|
1
|
+
"""Raw audio sample manipulation via Numpy-backed containers.
|
|
2
|
+
|
|
3
|
+
Everything in this module centers on :class:`Audio`, a thin wrapper around a
|
|
4
|
+
2D ``float32`` numpy array shaped ``(num_samples, num_channels)`` plus a
|
|
5
|
+
``sample_rate`` in Hz. By convention, sample values in ``[-1.0, 1.0]`` are
|
|
6
|
+
digital full-scale; values outside that range are valid in memory but clip on
|
|
7
|
+
playback or when written to most file formats.
|
|
8
|
+
|
|
9
|
+
Construct one from a numpy array, or load existing audio from disk or the web::
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pyquist as pq
|
|
13
|
+
|
|
14
|
+
sr = 44100
|
|
15
|
+
t = np.arange(sr) / sr
|
|
16
|
+
tone = pq.Audio(0.5 * np.sin(2 * np.pi * 440 * t), sample_rate=sr) # 1s of A4
|
|
17
|
+
|
|
18
|
+
riff = pq.Audio.from_file("guitar.wav")
|
|
19
|
+
drums = pq.Audio.from_url("https://example.com/drums.mp3")
|
|
20
|
+
|
|
21
|
+
``Audio`` behaves like a numpy array where it can — it supports indexing,
|
|
22
|
+
slicing, ``len()``, and elementwise arithmetic (``+``, ``-``, ``*``, ``/``,
|
|
23
|
+
in-place variants), all returning ``Audio``::
|
|
24
|
+
|
|
25
|
+
mix = riff + drums[: len(riff)] # sum the overlapping region
|
|
26
|
+
mix *= 0.5 # halve the amplitude in place
|
|
27
|
+
|
|
28
|
+
On top of that it offers music-specific helpers that return new ``Audio``
|
|
29
|
+
objects::
|
|
30
|
+
|
|
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")
|
|
34
|
+
|
|
35
|
+
See :meth:`Audio.zeros` for an empty destination buffer and
|
|
36
|
+
:meth:`Audio.concatenate` to join buffers end to end. To turn musical events
|
|
37
|
+
into ``Audio``, see :mod:`pyquist.score`.
|
|
38
|
+
"""
|
|
39
|
+
|
|
1
40
|
import pathlib
|
|
2
41
|
from io import BytesIO
|
|
3
42
|
from typing import IO, Optional, Union
|
|
4
43
|
from urllib.request import urlopen
|
|
5
44
|
|
|
6
45
|
import numpy as np
|
|
7
|
-
import resampy
|
|
8
46
|
import soundfile as sf
|
|
47
|
+
import soxr
|
|
9
48
|
|
|
10
49
|
from .helper import db_to_amplitude
|
|
11
50
|
|
|
@@ -103,6 +142,28 @@ class Audio:
|
|
|
103
142
|
"""
|
|
104
143
|
return cls.from_file(BytesIO(urlopen(url).read()))
|
|
105
144
|
|
|
145
|
+
@classmethod
|
|
146
|
+
def concatenate(cls, audios: "list[Audio]") -> "Audio":
|
|
147
|
+
"""Joins a sequence of ``Audio`` end-to-end along the sample axis.
|
|
148
|
+
|
|
149
|
+
All inputs must share a ``num_channels`` and a ``sample_rate``;
|
|
150
|
+
otherwise ``ValueError`` is raised. The list must be non-empty.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
audios: A non-empty list of ``Audio`` to join in order.
|
|
154
|
+
"""
|
|
155
|
+
audios = list(audios)
|
|
156
|
+
if not audios:
|
|
157
|
+
raise ValueError("concatenate requires at least one Audio.")
|
|
158
|
+
sample_rates = {a.sample_rate for a in audios}
|
|
159
|
+
if len(sample_rates) != 1:
|
|
160
|
+
raise ValueError(f"Inconsistent sample rates: {sample_rates}.")
|
|
161
|
+
channel_counts = {a.num_channels for a in audios}
|
|
162
|
+
if len(channel_counts) != 1:
|
|
163
|
+
raise ValueError(f"Inconsistent channel counts: {channel_counts}.")
|
|
164
|
+
samples = np.concatenate([a.samples for a in audios], axis=0)
|
|
165
|
+
return cls(samples, sample_rate=sample_rates.pop())
|
|
166
|
+
|
|
106
167
|
# --- Core attributes ----------------------------------------------------
|
|
107
168
|
|
|
108
169
|
@property
|
|
@@ -328,9 +389,9 @@ class Audio:
|
|
|
328
389
|
def resample(self, new_sample_rate: int, **kwargs) -> "Audio":
|
|
329
390
|
"""Returns a new ``Audio`` resampled to ``new_sample_rate``.
|
|
330
391
|
|
|
331
|
-
Resampling is performed by ``
|
|
332
|
-
filter; extra keyword arguments (e.g. ``
|
|
333
|
-
forwarded to :func:`
|
|
392
|
+
Resampling is performed by ``soxr`` using a bandlimited
|
|
393
|
+
sinc filter; extra keyword arguments (e.g. ``quality='VHQ'``) are
|
|
394
|
+
forwarded to :func:`soxr.resample`. The number of channels is
|
|
334
395
|
preserved; the number of samples scales by
|
|
335
396
|
``new_sample_rate / self.sample_rate``.
|
|
336
397
|
|
|
@@ -343,8 +404,8 @@ class Audio:
|
|
|
343
404
|
raise TypeError("new_sample_rate must be an int.")
|
|
344
405
|
if new_sample_rate <= 0:
|
|
345
406
|
raise ValueError("new_sample_rate must be positive.")
|
|
346
|
-
resampled =
|
|
347
|
-
self._samples, self._sample_rate, new_sample_rate,
|
|
407
|
+
resampled = soxr.resample(
|
|
408
|
+
self._samples, self._sample_rate, new_sample_rate, **kwargs
|
|
348
409
|
)
|
|
349
410
|
return Audio(resampled, sample_rate=new_sample_rate)
|
|
350
411
|
|
|
@@ -83,6 +83,31 @@ class TestAudio(unittest.TestCase):
|
|
|
83
83
|
with self.assertRaises(ValueError):
|
|
84
84
|
Audio.zeros(10, -1)
|
|
85
85
|
|
|
86
|
+
def test_concatenate_classmethod(self):
|
|
87
|
+
a = Audio(np.ones(10), sample_rate=44100)
|
|
88
|
+
b = Audio(np.zeros(5), sample_rate=44100)
|
|
89
|
+
joined = Audio.concatenate([a, b])
|
|
90
|
+
self.assertEqual(joined.shape, (15, 1))
|
|
91
|
+
self.assertEqual(joined.sample_rate, 44100)
|
|
92
|
+
self.assertTrue(np.all(joined.samples[:10] == 1.0))
|
|
93
|
+
self.assertTrue(np.all(joined.samples[10:] == 0.0))
|
|
94
|
+
|
|
95
|
+
# Stereo concatenation preserves channel count.
|
|
96
|
+
s1 = Audio(np.ones((4, 2)), sample_rate=22050)
|
|
97
|
+
s2 = Audio(np.zeros((3, 2)), sample_rate=22050)
|
|
98
|
+
self.assertEqual(Audio.concatenate([s1, s2]).shape, (7, 2))
|
|
99
|
+
|
|
100
|
+
with self.assertRaises(ValueError):
|
|
101
|
+
Audio.concatenate([])
|
|
102
|
+
with self.assertRaises(ValueError):
|
|
103
|
+
Audio.concatenate(
|
|
104
|
+
[Audio(np.ones(3), sample_rate=44100), Audio(np.ones(3), sample_rate=22050)]
|
|
105
|
+
)
|
|
106
|
+
with self.assertRaises(ValueError):
|
|
107
|
+
Audio.concatenate(
|
|
108
|
+
[Audio(np.ones((3, 1)), sample_rate=44100), Audio(np.ones((3, 2)), sample_rate=44100)]
|
|
109
|
+
)
|
|
110
|
+
|
|
86
111
|
def test_from_file_wav(self):
|
|
87
112
|
# 388954__fullmetaljedi__blues-riff-in-g-nylon.wav: stereo, 48 kHz.
|
|
88
113
|
audio = Audio.from_file(_BLUES_RIFF_WAV)
|
|
@@ -156,7 +181,9 @@ class TestAudio(unittest.TestCase):
|
|
|
156
181
|
audio = Audio.from_file(_BLUES_RIFF_WAV)
|
|
157
182
|
resampled = audio.resample(24000)
|
|
158
183
|
self.assertEqual(resampled.num_channels, 2)
|
|
159
|
-
|
|
184
|
+
# Output length follows new_rate/old_rate; allow ±1 for the
|
|
185
|
+
# resampler's rounding of a non-integer result.
|
|
186
|
+
self.assertAlmostEqual(resampled.num_samples, audio.num_samples / 2, delta=1)
|
|
160
187
|
self.assertEqual(resampled.sample_rate, 24000)
|
|
161
188
|
self.assertAlmostEqual(resampled.duration, audio.duration, places=3)
|
|
162
189
|
|
|
@@ -12,6 +12,7 @@ from typing import Any, Optional, Tuple, Union
|
|
|
12
12
|
|
|
13
13
|
import sounddevice as sd
|
|
14
14
|
import tqdm
|
|
15
|
+
import numpy as np
|
|
15
16
|
|
|
16
17
|
from .audio import Audio
|
|
17
18
|
from .paths import CACHE_DIR
|
|
@@ -95,6 +96,18 @@ def _in_ipython_notebook() -> bool:
|
|
|
95
96
|
return ipy.__class__.__name__ != "TerminalInteractiveShell"
|
|
96
97
|
|
|
97
98
|
|
|
99
|
+
def _in_browser() -> bool:
|
|
100
|
+
"""Returns True if running inside a browser-hosted Python runtime.
|
|
101
|
+
|
|
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`.
|
|
107
|
+
"""
|
|
108
|
+
return sys.platform == "emscripten"
|
|
109
|
+
|
|
110
|
+
|
|
98
111
|
def play(
|
|
99
112
|
audio: Audio,
|
|
100
113
|
*,
|
|
@@ -141,7 +154,12 @@ def play(
|
|
|
141
154
|
sd.wait()
|
|
142
155
|
|
|
143
156
|
|
|
144
|
-
def record(
|
|
157
|
+
def record(
|
|
158
|
+
duration: float,
|
|
159
|
+
*,
|
|
160
|
+
progress_bar: bool = True,
|
|
161
|
+
**kwargs: Any,
|
|
162
|
+
) -> Audio:
|
|
145
163
|
"""Records audio from the default input device.
|
|
146
164
|
|
|
147
165
|
Args:
|
|
@@ -151,6 +169,11 @@ def record(duration: float, *, progress_bar: bool = True, **kwargs: Any) -> Audi
|
|
|
151
169
|
Returns:
|
|
152
170
|
The recorded Audio at the input device's native sample rate.
|
|
153
171
|
"""
|
|
172
|
+
|
|
173
|
+
# :mod:`sounddevice` is not available when running in browser, handle separately.
|
|
174
|
+
if _in_browser():
|
|
175
|
+
return _record_in_browser(duration)
|
|
176
|
+
|
|
154
177
|
device_info = sd.query_devices(sd.default.device[0])
|
|
155
178
|
sample_rate = round(device_info["default_samplerate"])
|
|
156
179
|
num_channels = device_info["max_input_channels"]
|
|
@@ -170,6 +193,35 @@ def record(duration: float, *, progress_bar: bool = True, **kwargs: Any) -> Audi
|
|
|
170
193
|
return Audio(samples, sample_rate=sample_rate)
|
|
171
194
|
|
|
172
195
|
|
|
196
|
+
def _record_in_browser(duration: float) -> Audio:
|
|
197
|
+
"""Records via ``browseraudio`` (the Web Audio backend for :func:`record`).
|
|
198
|
+
|
|
199
|
+
Returns an empty ``Audio`` that fills in once the user clicks Record (read it
|
|
200
|
+
in a later cell); failures are printed to stderr.
|
|
201
|
+
"""
|
|
202
|
+
try:
|
|
203
|
+
import browseraudio
|
|
204
|
+
except ImportError as e:
|
|
205
|
+
raise RuntimeError(
|
|
206
|
+
"In-browser recording needs the 'browseraudio' package — install "
|
|
207
|
+
"pyquist[browser] (or `pip install browseraudio`)."
|
|
208
|
+
) from e
|
|
209
|
+
|
|
210
|
+
recorder = browseraudio.record(duration)
|
|
211
|
+
audio = Audio(np.zeros((1, 1), dtype=np.float32), sample_rate=None)
|
|
212
|
+
|
|
213
|
+
def _fill(rec) -> None:
|
|
214
|
+
audio.samples = rec.samples
|
|
215
|
+
audio.sample_rate = rec.sample_rate
|
|
216
|
+
|
|
217
|
+
# TODO: Figure out how to make this a synchronous, blocking call.
|
|
218
|
+
recorder.on_result(_fill)
|
|
219
|
+
recorder.on_error(
|
|
220
|
+
lambda msg: print(f"In-browser recording failed: {msg}", file=sys.stderr)
|
|
221
|
+
)
|
|
222
|
+
return audio
|
|
223
|
+
|
|
224
|
+
|
|
173
225
|
def _resolve_device(device_id_or_name: DeviceRef, kind: str) -> Tuple[int, str]:
|
|
174
226
|
"""Resolves an int ID or name substring to a ``(device_id, device_name)`` pair.
|
|
175
227
|
|
|
@@ -3,6 +3,7 @@ import io
|
|
|
3
3
|
import json
|
|
4
4
|
import tempfile
|
|
5
5
|
import unittest
|
|
6
|
+
import numpy as np
|
|
6
7
|
from pathlib import Path
|
|
7
8
|
from unittest import mock
|
|
8
9
|
|
|
@@ -504,5 +505,56 @@ class TestInIPythonNotebook(unittest.TestCase):
|
|
|
504
505
|
self.assertFalse(device._in_ipython_notebook())
|
|
505
506
|
|
|
506
507
|
|
|
508
|
+
class TestInBrowser(unittest.TestCase):
|
|
509
|
+
"""``_in_browser`` must recognise browser-hosted runtimes (Pyodide /
|
|
510
|
+
JupyterLite) so that ``record`` delegates to the Web Audio backend instead
|
|
511
|
+
of calling sounddevice, which would crash where there is no audio device."""
|
|
512
|
+
|
|
513
|
+
def test_emscripten_platform_detected(self):
|
|
514
|
+
with mock.patch.object(device.sys, "platform", "emscripten"):
|
|
515
|
+
self.assertTrue(device._in_browser())
|
|
516
|
+
|
|
517
|
+
def test_native_platform_not_detected(self):
|
|
518
|
+
for platform_name in ("darwin", "linux", "win32"):
|
|
519
|
+
with mock.patch.object(device.sys, "platform", platform_name):
|
|
520
|
+
self.assertFalse(device._in_browser())
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
class TestRecordDispatch(unittest.TestCase):
|
|
524
|
+
"""``record`` picks the right backend based on context."""
|
|
525
|
+
|
|
526
|
+
def test_uses_browser_in_browser(self):
|
|
527
|
+
sentinel = object()
|
|
528
|
+
with (
|
|
529
|
+
mock.patch.object(device, "_in_browser", return_value=True),
|
|
530
|
+
mock.patch.object(
|
|
531
|
+
device, "_record_in_browser", return_value=sentinel
|
|
532
|
+
) as mock_browser,
|
|
533
|
+
mock.patch.object(device.sd, "rec") as mock_rec,
|
|
534
|
+
):
|
|
535
|
+
result = device.record(1.0, progress_bar=False)
|
|
536
|
+
self.assertIs(result, sentinel)
|
|
537
|
+
mock_browser.assert_called_once_with(1.0)
|
|
538
|
+
mock_rec.assert_not_called()
|
|
539
|
+
|
|
540
|
+
def test_uses_sounddevice_outside_browser(self):
|
|
541
|
+
with (
|
|
542
|
+
mock.patch.object(device, "_in_browser", return_value=False),
|
|
543
|
+
mock.patch.object(device, "_record_in_browser") as mock_browser,
|
|
544
|
+
mock.patch.object(
|
|
545
|
+
device.sd,
|
|
546
|
+
"query_devices",
|
|
547
|
+
return_value={"default_samplerate": 44100, "max_input_channels": 1},
|
|
548
|
+
),
|
|
549
|
+
mock.patch.object(
|
|
550
|
+
device.sd, "rec", return_value=np.zeros((44100, 1), dtype=np.float32)
|
|
551
|
+
) as mock_rec,
|
|
552
|
+
mock.patch.object(device.sd, "wait"),
|
|
553
|
+
):
|
|
554
|
+
device.record(1.0, progress_bar=False)
|
|
555
|
+
mock_rec.assert_called_once()
|
|
556
|
+
mock_browser.assert_not_called()
|
|
557
|
+
|
|
558
|
+
|
|
507
559
|
if __name__ == "__main__":
|
|
508
560
|
unittest.main()
|
|
@@ -5,6 +5,30 @@ A :class:`Score` is a list of :class:`Event` — onset-based musical events.
|
|
|
5
5
|
:class:`collections.UserList`): you can iterate, index, slice, concatenate
|
|
6
6
|
with ``+``, repeat with ``*``, append, etc. — all preserving ``Score`` type.
|
|
7
7
|
|
|
8
|
+
A minimal end-to-end example — build a score, define an instrument, render it
|
|
9
|
+
to :class:`~pyquist.audio.Audio`::
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pyquist as pq
|
|
13
|
+
from pyquist.helper import pitch_to_frequency
|
|
14
|
+
from pyquist.score import Score, BasicMetronome
|
|
15
|
+
|
|
16
|
+
# Each (time, kwargs) tuple is one event; Score coerces tuples to Events.
|
|
17
|
+
score = Score([
|
|
18
|
+
(0, {"pitch": 60, "duration": 0.5}),
|
|
19
|
+
(1, {"pitch": 64, "duration": 0.5}),
|
|
20
|
+
])
|
|
21
|
+
|
|
22
|
+
def sine(pitch, duration, sample_rate=44100, **kwargs):
|
|
23
|
+
t = np.arange(int(duration * sample_rate)) / sample_rate
|
|
24
|
+
freq = pitch_to_frequency(pitch)
|
|
25
|
+
return pq.Audio(0.3 * np.sin(2 * np.pi * freq * t), sample_rate=sample_rate)
|
|
26
|
+
|
|
27
|
+
# With a metronome, event times are beats; at 120 BPM, 1 beat = 0.5 s.
|
|
28
|
+
audio = score.render(sine, metronome=BasicMetronome(bpm=120))
|
|
29
|
+
|
|
30
|
+
The rest of this module fills in the details behind that flow.
|
|
31
|
+
|
|
8
32
|
Each event carries a ``time`` (in *seconds* if rendered without a metronome,
|
|
9
33
|
in *ticks* otherwise — a "tick" being whatever discrete time unit the
|
|
10
34
|
metronome maps to seconds) and an instrument-specific ``kwargs`` dict. The
|
|
@@ -81,12 +105,40 @@ class Event(NamedTuple):
|
|
|
81
105
|
``Event`` is a ``NamedTuple``: it unpacks like a regular tuple
|
|
82
106
|
(``time, kwargs = event``), can be constructed positionally
|
|
83
107
|
(``Event(0.5, {"pitch": 60})``) or by keyword.
|
|
108
|
+
|
|
109
|
+
You rarely need to construct an ``Event`` explicitly: :class:`Score`
|
|
110
|
+
converts any ``(time, kwargs)`` 2-tuple into an ``Event`` automatically, so
|
|
111
|
+
``Score([(0.0, {"pitch": 60})])`` and ``Score([Event(0.0, {"pitch": 60})])``
|
|
112
|
+
are equivalent.
|
|
84
113
|
"""
|
|
85
114
|
|
|
86
115
|
time: float
|
|
87
116
|
kwargs: _KwargsDict
|
|
88
117
|
|
|
89
118
|
|
|
119
|
+
def _coerce_event(item: Union["Event", Tuple[float, _KwargsDict]]) -> "Event":
|
|
120
|
+
"""Returns ``item`` as an :class:`Event`, coercing a bare 2-tuple.
|
|
121
|
+
|
|
122
|
+
Accepts an existing :class:`Event` (returned unchanged) or a
|
|
123
|
+
``(time, kwargs)`` tuple where ``time`` is a real number and ``kwargs`` is
|
|
124
|
+
a ``dict``. Anything else raises ``TypeError``.
|
|
125
|
+
"""
|
|
126
|
+
if isinstance(item, Event):
|
|
127
|
+
return item
|
|
128
|
+
if (
|
|
129
|
+
isinstance(item, tuple)
|
|
130
|
+
and len(item) == 2
|
|
131
|
+
and isinstance(item[0], (int, float))
|
|
132
|
+
and not isinstance(item[0], bool)
|
|
133
|
+
and isinstance(item[1], dict)
|
|
134
|
+
):
|
|
135
|
+
return Event(float(item[0]), item[1])
|
|
136
|
+
raise TypeError(
|
|
137
|
+
"Score items must be Event or (time: float, kwargs: dict) tuples; "
|
|
138
|
+
f"got {item!r}."
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
90
142
|
# A callable invoked as ``instrument(**event.kwargs)`` that returns the
|
|
91
143
|
# rendered Audio for one event. Declare the kwargs you use and absorb the
|
|
92
144
|
# rest with ``**kwargs``.
|
|
@@ -116,22 +168,50 @@ class Metronome(abc.ABC):
|
|
|
116
168
|
|
|
117
169
|
|
|
118
170
|
class BasicMetronome(Metronome):
|
|
119
|
-
"""A fixed-tempo metronome
|
|
171
|
+
"""A fixed-tempo metronome: a constant number of ticks per second.
|
|
172
|
+
|
|
173
|
+
A *tick* is the canonical unit of score time (see :class:`Metronome`).
|
|
174
|
+
Depending on the score it might stand for a beat, a MIDI tick, a second, or
|
|
175
|
+
any other unit — ``BasicMetronome`` just maps ticks to seconds at a single
|
|
176
|
+
constant rate, :attr:`ticks_per_second`.
|
|
120
177
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
178
|
+
Set that rate with *exactly one* of two keyword arguments:
|
|
179
|
+
|
|
180
|
+
* ``tps`` — ticks per second, the canonical parameter. The default,
|
|
181
|
+
``tps=1.0``, makes 1 tick = 1 second: an identity mapping convenient for
|
|
182
|
+
scores whose ``time`` field is already in seconds.
|
|
183
|
+
* ``bpm`` — beats per minute, a musical convenience for the common case
|
|
184
|
+
where a tick is a beat. BPM is just that same rate expressed per minute
|
|
185
|
+
rather than per second, converted internally via ``tps = bpm / 60`` — so
|
|
186
|
+
``BasicMetronome(bpm=120)`` is exactly ``BasicMetronome(tps=2.0)``. When
|
|
187
|
+
given, ``bpm`` takes precedence over ``tps``.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
tps: Ticks per second. Defaults to ``1.0`` (1 tick = 1 second).
|
|
191
|
+
bpm: Beats per minute. If given, overrides ``tps`` (``tps = bpm / 60``).
|
|
192
|
+
|
|
193
|
+
Raises:
|
|
194
|
+
ValueError: if both ``tps`` and ``bpm`` are ``None``.
|
|
124
195
|
"""
|
|
125
196
|
|
|
126
|
-
def __init__(
|
|
127
|
-
self
|
|
128
|
-
|
|
197
|
+
def __init__(
|
|
198
|
+
self,
|
|
199
|
+
*,
|
|
200
|
+
tps: Optional[float] = 1.0,
|
|
201
|
+
bpm: Optional[float] = None,
|
|
202
|
+
):
|
|
203
|
+
if bpm is not None:
|
|
204
|
+
tps = bpm / 60.0
|
|
205
|
+
if tps is None:
|
|
206
|
+
raise ValueError("Specify exactly one of bpm or tps.")
|
|
207
|
+
self.ticks_per_second = tps
|
|
208
|
+
self.seconds_per_tick = 1.0 / tps
|
|
129
209
|
|
|
130
210
|
def tick_to_seconds(self, tick: float) -> float:
|
|
131
|
-
return tick * self.
|
|
211
|
+
return tick * self.seconds_per_tick
|
|
132
212
|
|
|
133
213
|
def seconds_to_tick(self, seconds: float) -> float:
|
|
134
|
-
return seconds
|
|
214
|
+
return seconds * self.ticks_per_second
|
|
135
215
|
|
|
136
216
|
|
|
137
217
|
# ---------------------------------------------------------------------------
|
|
@@ -152,13 +232,38 @@ class Score(UserList):
|
|
|
152
232
|
metronome is not stored on the score — keep it as a separate variable
|
|
153
233
|
(or use the ``(score, metronome)`` tuple returned by :meth:`from_midi`).
|
|
154
234
|
|
|
155
|
-
Construct from any iterable of events
|
|
235
|
+
Construct from any iterable of events. Bare ``(time, kwargs)`` tuples are
|
|
236
|
+
converted to :class:`Event` automatically, so these are equivalent::
|
|
156
237
|
|
|
157
238
|
Score([Event(0.0, {"pitch": 60}), Event(1.0, {"pitch": 64})])
|
|
239
|
+
Score([(0.0, {"pitch": 60}), (1.0, {"pitch": 64})])
|
|
158
240
|
|
|
159
241
|
Or load from a MIDI file via :meth:`from_midi`.
|
|
160
242
|
"""
|
|
161
243
|
|
|
244
|
+
def __init__(self, initlist=None):
|
|
245
|
+
"""Builds a ``Score``, coercing any ``(time, kwargs)`` tuples to events."""
|
|
246
|
+
super().__init__()
|
|
247
|
+
if initlist is not None:
|
|
248
|
+
self.data = [_coerce_event(item) for item in initlist]
|
|
249
|
+
|
|
250
|
+
# --- list mutation (coerce tuples to Event) ----------------------------
|
|
251
|
+
|
|
252
|
+
def __setitem__(self, index, value):
|
|
253
|
+
if isinstance(index, slice):
|
|
254
|
+
self.data[index] = [_coerce_event(v) for v in value]
|
|
255
|
+
else:
|
|
256
|
+
self.data[index] = _coerce_event(value)
|
|
257
|
+
|
|
258
|
+
def append(self, item) -> None:
|
|
259
|
+
self.data.append(_coerce_event(item))
|
|
260
|
+
|
|
261
|
+
def insert(self, index, item) -> None:
|
|
262
|
+
self.data.insert(index, _coerce_event(item))
|
|
263
|
+
|
|
264
|
+
def extend(self, other) -> None:
|
|
265
|
+
self.data.extend(_coerce_event(item) for item in other)
|
|
266
|
+
|
|
162
267
|
# --- properties --------------------------------------------------------
|
|
163
268
|
|
|
164
269
|
@property
|
|
@@ -55,6 +55,30 @@ class TestScoreListBehavior(unittest.TestCase):
|
|
|
55
55
|
def test_empty_construction(self):
|
|
56
56
|
self.assertEqual(len(Score()), 0)
|
|
57
57
|
|
|
58
|
+
def test_tuple_coercion(self):
|
|
59
|
+
# Bare (time, kwargs) tuples are coerced to Event on construction.
|
|
60
|
+
score = Score([(0.0, {"pitch": 60}), (1.0, {"pitch": 64})])
|
|
61
|
+
self.assertTrue(all(isinstance(e, Event) for e in score))
|
|
62
|
+
self.assertEqual(score[0], Event(0.0, {"pitch": 60}))
|
|
63
|
+
self.assertIsInstance(score[0].time, float)
|
|
64
|
+
|
|
65
|
+
# Coercion also applies to append, insert, extend, and setitem.
|
|
66
|
+
score.append((2.0, {"pitch": 67}))
|
|
67
|
+
score.insert(0, (-1.0, {"pitch": 48}))
|
|
68
|
+
score.extend([(3.0, {"pitch": 72})])
|
|
69
|
+
score[1] = (0.5, {"pitch": 50})
|
|
70
|
+
self.assertTrue(all(isinstance(e, Event) for e in score))
|
|
71
|
+
|
|
72
|
+
# Malformed tuples raise TypeError.
|
|
73
|
+
for bad in [(0.0,), (0.0, "x"), ("a", {}), (True, {})]:
|
|
74
|
+
with self.assertRaises(TypeError):
|
|
75
|
+
Score([bad])
|
|
76
|
+
|
|
77
|
+
def test_concatenation_preserves_event_coercion(self):
|
|
78
|
+
score = Score([(0.0, {"pitch": 60})]) + Score([(1.0, {"pitch": 64})])
|
|
79
|
+
self.assertIsInstance(score, Score)
|
|
80
|
+
self.assertTrue(all(isinstance(e, Event) for e in score))
|
|
81
|
+
|
|
58
82
|
def test_append_and_iterate(self):
|
|
59
83
|
score = Score()
|
|
60
84
|
score.append(Event(0.0, {}))
|
|
@@ -167,20 +191,46 @@ class TestScoreSegment(unittest.TestCase):
|
|
|
167
191
|
|
|
168
192
|
class TestBasicMetronome(unittest.TestCase):
|
|
169
193
|
def test_basic(self):
|
|
170
|
-
m = BasicMetronome(120)
|
|
171
|
-
self.assertEqual(m.
|
|
172
|
-
self.assertEqual(m.
|
|
194
|
+
m = BasicMetronome(bpm=120)
|
|
195
|
+
self.assertEqual(m.ticks_per_second, 2.0)
|
|
196
|
+
self.assertEqual(m.seconds_per_tick, 0.5)
|
|
173
197
|
self.assertEqual(m.tick_to_seconds(1.0), 0.5)
|
|
174
198
|
self.assertEqual(m.seconds_to_tick(0.5), 1.0)
|
|
175
199
|
|
|
200
|
+
def test_default_is_identity(self):
|
|
201
|
+
# Default tps=1.0 → 1 tick = 1 second (60 BPM).
|
|
202
|
+
m = BasicMetronome()
|
|
203
|
+
self.assertEqual(m.ticks_per_second, 1.0)
|
|
204
|
+
self.assertEqual(m.seconds_per_tick, 1.0)
|
|
205
|
+
|
|
176
206
|
def test_60_bpm(self):
|
|
177
|
-
m = BasicMetronome(60)
|
|
178
|
-
self.assertEqual(m.
|
|
207
|
+
m = BasicMetronome(bpm=60)
|
|
208
|
+
self.assertEqual(m.seconds_per_tick, 1.0)
|
|
179
209
|
self.assertEqual(m.tick_to_seconds(1.0), 1.0)
|
|
180
210
|
self.assertEqual(m.seconds_to_tick(1.0), 1.0)
|
|
181
211
|
|
|
212
|
+
def test_tps(self):
|
|
213
|
+
# tps is ticks per second: 2 tps = 120 BPM.
|
|
214
|
+
m = BasicMetronome(tps=2.0)
|
|
215
|
+
self.assertEqual(m.ticks_per_second, 2.0)
|
|
216
|
+
self.assertEqual(m.seconds_per_tick, 0.5)
|
|
217
|
+
|
|
218
|
+
def test_bpm_equivalent_to_tps(self):
|
|
219
|
+
# bpm is just the rate per minute: bpm=120 == tps=2.0.
|
|
220
|
+
self.assertEqual(
|
|
221
|
+
BasicMetronome(bpm=120).ticks_per_second,
|
|
222
|
+
BasicMetronome(tps=2.0).ticks_per_second,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
def test_bpm_overrides_default_tps(self):
|
|
226
|
+
self.assertEqual(BasicMetronome(bpm=90).ticks_per_second, 1.5)
|
|
227
|
+
|
|
228
|
+
def test_neither_defined_raises(self):
|
|
229
|
+
with self.assertRaises(ValueError):
|
|
230
|
+
BasicMetronome(tps=None)
|
|
231
|
+
|
|
182
232
|
def test_round_trip(self):
|
|
183
|
-
m = BasicMetronome(140)
|
|
233
|
+
m = BasicMetronome(bpm=140)
|
|
184
234
|
for tick in [0.0, 1.0, 2.5, 17.3]:
|
|
185
235
|
self.assertAlmostEqual(m.seconds_to_tick(m.tick_to_seconds(tick)), tick)
|
|
186
236
|
|
|
@@ -286,7 +336,7 @@ class TestScoreRender(unittest.TestCase):
|
|
|
286
336
|
|
|
287
337
|
def test_metronome_converts_ticks(self):
|
|
288
338
|
# 60_000 BPM → 1 tick = 0.001s = 1 sample @ sr=1000.
|
|
289
|
-
m = BasicMetronome(60_000)
|
|
339
|
+
m = BasicMetronome(bpm=60_000)
|
|
290
340
|
score = Score([Event(5.0, {"value": 0.5, "duration": 0.01})])
|
|
291
341
|
audio = score.render(_const_tone, metronome=m)
|
|
292
342
|
self.assertTrue(np.all(audio.samples[:5] == 0.0))
|
|
Binary file
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Test data attributions
|
|
2
|
+
|
|
3
|
+
## `232009__danmitch3ll__xylophone-sweep.wav`
|
|
4
|
+
|
|
5
|
+
`Xylophone Sweep by DANMITCH3LL -- https://freesound.org/s/232009/ -- License: Attribution 4.0`
|
|
6
|
+
|
|
7
|
+
## `388954__fullmetaljedi__blues-riff-in-g-nylon.wav`
|
|
8
|
+
|
|
9
|
+
`Blues Riff in G (Nylon).wav by FullMetalJedi -- https://freesound.org/s/388954/ -- License: Creative Commons 0`
|
|
10
|
+
|
|
11
|
+
## `434013__mrpearch__drum-patern.mp3`
|
|
12
|
+
|
|
13
|
+
``Drum Patern.mp3 by MrPearch -- https://freesound.org/s/434013/ -- License: Creative Commons 0`
|
|
14
|
+
|
|
15
|
+
## `ravel_bolero.mid`
|
|
16
|
+
|
|
17
|
+
MIDI score of Ravel's _Bolero_. Entered US public domain in 2025.
|
|
@@ -30,6 +30,13 @@ _THEORYTAB_ID_LENGTH = 11
|
|
|
30
30
|
|
|
31
31
|
_HOOKTHEORY_API_URL = "https://api.hooktheory.com/v1/songs/public"
|
|
32
32
|
|
|
33
|
+
# Supported time signatures as (numBeats, beatUnit) pairs: 3/4, 4/4, 6/8.
|
|
34
|
+
# TheoryTab encodes the meter as a count of beats per measure (3, 4, or 6) with
|
|
35
|
+
# beatUnit 1; a song's beat/duration values and its tempo are all expressed in
|
|
36
|
+
# that same beat unit (quarter notes for 3/4 and 4/4, eighth notes for 6/8), so
|
|
37
|
+
# they render correctly against the tempo regardless of the time signature.
|
|
38
|
+
_SUPPORTED_METERS = {(3, 1), (4, 1), (6, 1)}
|
|
39
|
+
|
|
33
40
|
# Diatonic scales as ordered (whole-/half-) step intervals between successive
|
|
34
41
|
# notes. Each tuple has 6 entries (7 notes → 6 gaps).
|
|
35
42
|
_THEORYTAB_SCALE_NAME_TO_PITCH_INTERVALS = {
|
|
@@ -94,7 +101,7 @@ def _theorytab_chord_to_pitches(
|
|
|
94
101
|
|
|
95
102
|
Handles type (triad / 7 / 9 / ...), suspensions, additions, omissions,
|
|
96
103
|
alterations, borrowed scales, and secondary dominants. Returns the chord
|
|
97
|
-
in root position (no inversions).
|
|
104
|
+
in root position (no inversions). ``chord`` is not modified.
|
|
98
105
|
"""
|
|
99
106
|
# Build chord scale degrees
|
|
100
107
|
chord_degrees = set(range(1, chord["type"] + 1, 2))
|
|
@@ -145,15 +152,16 @@ def _theorytab_chord_to_pitches(
|
|
|
145
152
|
major_scale_intervals = _cumulative_intervals(
|
|
146
153
|
_THEORYTAB_SCALE_NAME_TO_PITCH_INTERVALS["major"]
|
|
147
154
|
)
|
|
155
|
+
root = chord["root"]
|
|
148
156
|
if chord["applied"] > 0:
|
|
149
|
-
key_tonic_pc = (key_tonic_pc + key_scale_intervals[
|
|
150
|
-
|
|
157
|
+
key_tonic_pc = (key_tonic_pc + key_scale_intervals[root - 1]) % 12
|
|
158
|
+
root = chord["applied"]
|
|
151
159
|
key_scale_intervals = major_scale_intervals
|
|
152
160
|
|
|
153
161
|
# Convert scale degrees to pitch offsets
|
|
154
162
|
chord_degree_to_interval = {}
|
|
155
163
|
for d in chord_degrees_list:
|
|
156
|
-
d_abs = (
|
|
164
|
+
d_abs = (root - 1) + (d - 1)
|
|
157
165
|
interval = key_scale_intervals[d_abs % 7]
|
|
158
166
|
interval += 12 * (d_abs // 7)
|
|
159
167
|
chord_degree_to_interval[d] = interval
|
|
@@ -253,6 +261,7 @@ def theorytab_json_to_score(
|
|
|
253
261
|
song_data: dict,
|
|
254
262
|
*,
|
|
255
263
|
durations_in_beats: bool = False,
|
|
264
|
+
harmony_as_notes: bool = True,
|
|
256
265
|
melody_octave: int = 5,
|
|
257
266
|
harmony_octave: int = 4,
|
|
258
267
|
) -> Tuple[Metronome, Score, Score]:
|
|
@@ -262,9 +271,10 @@ def theorytab_json_to_score(
|
|
|
262
271
|
with the returned :class:`BasicMetronome` when rendering so beats are
|
|
263
272
|
converted to seconds.
|
|
264
273
|
|
|
265
|
-
|
|
266
|
-
root position, each with a ``"pitch"`` kwarg — so a triad at
|
|
267
|
-
becomes three events sharing ``time == 4.0``.
|
|
274
|
+
By default, chord events are emitted as one :class:`Event` per chord
|
|
275
|
+
tone in root position, each with a ``"pitch"`` kwarg — so a triad at
|
|
276
|
+
beat 4 becomes three events sharing ``time == 4.0``. Set
|
|
277
|
+
``harmony_as_notes=False`` for one event per chord instead.
|
|
268
278
|
|
|
269
279
|
Args:
|
|
270
280
|
song_data: TheoryTab JSON (as returned by :func:`fetch_theorytab_json`).
|
|
@@ -272,6 +282,12 @@ def theorytab_json_to_score(
|
|
|
272
282
|
``kwargs["duration"]`` is converted to **seconds** via the
|
|
273
283
|
song's tempo. If ``True``, durations stay in beats and the
|
|
274
284
|
instrument is responsible for any further conversion.
|
|
285
|
+
harmony_as_notes: If ``True`` (default), the harmony score holds one
|
|
286
|
+
event per chord tone, with kwargs ``{"duration", "pitch"}``. If
|
|
287
|
+
``False``, it holds one event per chord, with kwargs
|
|
288
|
+
``{"duration", "root", "intervals", "inversion"}`` — ``root`` is
|
|
289
|
+
the root's MIDI pitch, ``intervals`` are the semitone gaps
|
|
290
|
+
between successive chord tones in root position.
|
|
275
291
|
melody_octave: Octave offset added to melody pitches.
|
|
276
292
|
harmony_octave: Octave offset added to harmony pitches.
|
|
277
293
|
|
|
@@ -284,13 +300,13 @@ def theorytab_json_to_score(
|
|
|
284
300
|
NotImplementedError: if the song's time signature / tempo / key
|
|
285
301
|
structure is more complex than this parser supports.
|
|
286
302
|
"""
|
|
287
|
-
# We only support single-section songs in 3/4
|
|
303
|
+
# We only support single-section songs in 3/4, 4/4, or 6/8, single-tempo,
|
|
304
|
+
# single-key. See _SUPPORTED_METERS for the meter encoding.
|
|
288
305
|
meters = song_data["meters"]
|
|
289
306
|
if (
|
|
290
307
|
len(meters) != 1
|
|
291
308
|
or meters[0]["beat"] != 1
|
|
292
|
-
or meters[0]["numBeats"] not in
|
|
293
|
-
or meters[0]["beatUnit"] != 1
|
|
309
|
+
or (meters[0]["numBeats"], meters[0]["beatUnit"]) not in _SUPPORTED_METERS
|
|
294
310
|
):
|
|
295
311
|
raise NotImplementedError(
|
|
296
312
|
"This song has an unsupported time signature. Try a different one."
|
|
@@ -306,7 +322,7 @@ def theorytab_json_to_score(
|
|
|
306
322
|
"This song has an unsupported key signature. Try a different one."
|
|
307
323
|
)
|
|
308
324
|
|
|
309
|
-
metronome = BasicMetronome(tempos[0]["bpm"])
|
|
325
|
+
metronome = BasicMetronome(bpm=tempos[0]["bpm"])
|
|
310
326
|
key = keys[0]
|
|
311
327
|
|
|
312
328
|
# Parse melody
|
|
@@ -332,11 +348,24 @@ def theorytab_json_to_score(
|
|
|
332
348
|
if not durations_in_beats:
|
|
333
349
|
duration = metronome.tick_to_seconds(duration)
|
|
334
350
|
pitches = _theorytab_chord_to_pitches(chord, key)
|
|
335
|
-
|
|
351
|
+
if harmony_as_notes:
|
|
352
|
+
for pitch in pitches:
|
|
353
|
+
harmony.append(
|
|
354
|
+
Event(
|
|
355
|
+
beat,
|
|
356
|
+
{"duration": duration, "pitch": pitch + harmony_octave * 12},
|
|
357
|
+
)
|
|
358
|
+
)
|
|
359
|
+
else:
|
|
336
360
|
harmony.append(
|
|
337
361
|
Event(
|
|
338
362
|
beat,
|
|
339
|
-
{
|
|
363
|
+
{
|
|
364
|
+
"duration": duration,
|
|
365
|
+
"root": pitches[0] + harmony_octave * 12,
|
|
366
|
+
"intervals": list(np.diff(pitches)),
|
|
367
|
+
"inversion": chord["inversion"],
|
|
368
|
+
},
|
|
340
369
|
)
|
|
341
370
|
)
|
|
342
371
|
harmony.sort(key=lambda e: e.time)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyquist
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.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
|
|
@@ -27,10 +27,12 @@ Requires-Dist: matplotlib
|
|
|
27
27
|
Requires-Dist: mido
|
|
28
28
|
Requires-Dist: numpy>=2.0
|
|
29
29
|
Requires-Dist: requests
|
|
30
|
-
Requires-Dist: resampy
|
|
31
30
|
Requires-Dist: sounddevice
|
|
32
31
|
Requires-Dist: soundfile
|
|
32
|
+
Requires-Dist: soxr
|
|
33
33
|
Requires-Dist: tqdm
|
|
34
|
+
Provides-Extra: browser
|
|
35
|
+
Requires-Dist: browseraudio>=0.3.0; extra == "browser"
|
|
34
36
|
Provides-Extra: dev
|
|
35
37
|
Requires-Dist: mypy>=1.13; extra == "dev"
|
|
36
38
|
Requires-Dist: pre-commit>=4.0; extra == "dev"
|
|
@@ -69,8 +71,10 @@ pq.plot_spec(audio) # spectrogram
|
|
|
69
71
|
Loading and transforming:
|
|
70
72
|
|
|
71
73
|
```python
|
|
72
|
-
|
|
73
|
-
|
|
74
|
+
from pyquist.paths import TEST_DATA_DIR
|
|
75
|
+
|
|
76
|
+
riff = pq.Audio.from_file(
|
|
77
|
+
TEST_DATA_DIR / "388954__fullmetaljedi__blues-riff-in-g-nylon.wav"
|
|
74
78
|
)
|
|
75
79
|
clip = riff.segment(offset=5.0, duration=3.0).resample(8000)
|
|
76
80
|
pq.play(clip)
|
|
@@ -79,7 +83,7 @@ pq.play(clip)
|
|
|
79
83
|
Rendering a `Score` with a custom instrument. An instrument is called as `instrument(**event.kwargs)` — declare the kwargs you use and absorb the rest with `**kwargs`:
|
|
80
84
|
|
|
81
85
|
```python
|
|
82
|
-
from pyquist.score import Score,
|
|
86
|
+
from pyquist.score import Score, BasicMetronome
|
|
83
87
|
from pyquist.helper import pitch_to_frequency
|
|
84
88
|
|
|
85
89
|
def sine_instrument(pitch, duration, **kwargs):
|
|
@@ -89,11 +93,11 @@ def sine_instrument(pitch, duration, **kwargs):
|
|
|
89
93
|
return pq.Audio(0.3 * np.sin(2 * np.pi * freq * t) * np.exp(-3 * t), sample_rate=sr)
|
|
90
94
|
|
|
91
95
|
score = Score([
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
96
|
+
(0, {"pitch": 60, "duration": 0.5}),
|
|
97
|
+
(1, {"pitch": 64, "duration": 0.5}),
|
|
98
|
+
(2, {"pitch": 67, "duration": 0.5}),
|
|
95
99
|
])
|
|
96
|
-
pq.play(score.render(sine_instrument, metronome=BasicMetronome(120)))
|
|
100
|
+
pq.play(score.render(sine_instrument, metronome=BasicMetronome(bpm=120)))
|
|
97
101
|
```
|
|
98
102
|
|
|
99
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).
|
|
@@ -21,8 +21,10 @@ pyquist.egg-info/dependency_links.txt
|
|
|
21
21
|
pyquist.egg-info/entry_points.txt
|
|
22
22
|
pyquist.egg-info/requires.txt
|
|
23
23
|
pyquist.egg-info/top_level.txt
|
|
24
|
+
pyquist/test_data/232009__danmitch3ll__xylophone-sweep.wav
|
|
24
25
|
pyquist/test_data/388954__fullmetaljedi__blues-riff-in-g-nylon.wav
|
|
25
26
|
pyquist/test_data/434013__mrpearch__drum-patern.mp3
|
|
27
|
+
pyquist/test_data/ATTRIBUTION.md
|
|
26
28
|
pyquist/test_data/ravel_bolero.mid
|
|
27
29
|
pyquist/web/__init__.py
|
|
28
30
|
pyquist/web/freesound.py
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{pyquist-0.1.0 → pyquist-0.2.0}/pyquist/test_data/388954__fullmetaljedi__blues-riff-in-g-nylon.wav
RENAMED
|
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
|