hum 1.0.4__tar.gz → 1.0.6__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.
hum-1.0.6/PKG-INFO ADDED
@@ -0,0 +1,563 @@
1
+ Metadata-Version: 2.1
2
+ Name: hum
3
+ Version: 1.0.6
4
+ Summary: A python synthesizer for creating and manipulating audio signals.
5
+ Home-page: https://github.com/thorwhalen/hum
6
+ License: mit
7
+ Keywords: signal processing,audio generation,data,synthesizer,sonification
8
+ Platform: any
9
+ Description-Content-Type: text/markdown
10
+ Provides-Extra: testing
11
+ License-File: LICENSE
12
+
13
+ # hum
14
+
15
+ A python synthesizer for creating and manipulating audio signals.
16
+
17
+ To install: ```pip install hum```
18
+
19
+ Note: Some functionalities depend on [pyo](https://belangeo.github.io/pyo/download.html),
20
+ which itself requires some tools (namely, [portaudio](https://www.portaudio.com/)
21
+ and [Portmidi](https://github.com/PortMidi/portmidi)) that _may_ have to be
22
+ installed manually.
23
+
24
+ ## Overview
25
+
26
+ The `Synth` class is a powerful wrapper around Pyo's audio engine, providing:
27
+
28
+ 1. **Real-time parameter control** - Change audio parameters (knobs) during playback
29
+ 2. **Event recording** - Automatically record all parameter changes with timestamps
30
+ 3. **Event playback** - Replay recorded events exactly as they happened
31
+ 4. **Event rendering** - Convert recorded events into audio files
32
+ 5. **Context manager** - Clean resource management with `with` statements
33
+
34
+ ## Getting Started with Synth
35
+
36
+ ```python
37
+ from hum.pyo_util import Synth
38
+ ```
39
+
40
+ ## Simple Synth Test
41
+
42
+ Let's start with a simple sine wave synthesizer that demonstrates the basic functionality:
43
+
44
+ ```python
45
+ import time
46
+ from pyo import Sine
47
+ import recode
48
+ from hum.pyo_util import Synth, DFLT_PYO_SR, round_event_times
49
+ from hum.extra_util import estimate_frequencies
50
+
51
+ base_freq = 220
52
+
53
+ # Make a synth that plays a simple sine wave
54
+ def simple_sine(freq=base_freq):
55
+ return Sine(freq=freq)
56
+
57
+ s = Synth(simple_sine)
58
+
59
+ # Define a sequence of frequencies to play
60
+ freq_sequence = [base_freq] + [base_freq * 3 / 2, base_freq * 2]
61
+
62
+ # Play the frequencies in sequence
63
+ with s:
64
+ time.sleep(1) # let base_freq play for a second
65
+ s(freq=freq_sequence[1]) # Change to 330 Hz
66
+ time.sleep(1) # play that for a second
67
+ s['freq'] = freq_sequence[2] # Change to 440 Hz (alternative syntax)
68
+ time.sleep(1) # play that for a second
69
+ # The context manager exits here, which stops the synth
70
+ ```
71
+
72
+ After playing the synth, you can retrieve the recorded events:
73
+
74
+ ```python
75
+ # Get the recorded events
76
+ events = s.get_recording()
77
+
78
+ # Round timestamps for better readability
79
+ events = list(round_event_times(events, round_to=0.1))
80
+
81
+ # These are the events we expect to see:
82
+ expected_events = [
83
+ (
84
+ 0.0,
85
+ {
86
+ # First event contains the synth's initial parameters
87
+ 'freq': {'value': 220, 'time': 0.025, 'mul': 1, 'add': 0},
88
+ },
89
+ ),
90
+ (1.0, {'freq': 330.0}), # Second event at 1.0 seconds
91
+ (2.0, {'freq': 440}), # Third event at 2.0 seconds
92
+ (3.0, {}), # Final event marks the end of recording
93
+ ]
94
+
95
+ # Verify that we got what we expected
96
+ assert events == expected_events
97
+ ```
98
+
99
+ You can render these events to audio:
100
+
101
+ ```python
102
+ # Render events to WAV format bytes
103
+ wav_bytes = s.render_events(events)
104
+
105
+ # Decode and verify the WAV bytes
106
+ wf, sr = recode.decode_wav_bytes(wav_bytes)
107
+ assert sr == DFLT_PYO_SR
108
+ total_duration = len(wf) / sr
109
+ assert abs(total_duration - 3.0) < 0.1
110
+ ```
111
+
112
+ This simple example demonstrates the core functionality of the `Synth` class:
113
+ - Creating a synthesizer with a function that returns a Pyo object
114
+ - Playing the synth with real-time parameter changes
115
+ - Recording parameter changes as events
116
+ - Rendering events to audio
117
+
118
+ ## Interactive Usage in a REPL
119
+
120
+ For more interactive work, you can use the `Synth` class in a REPL environment. This allows you to experiment with different parameters in real-time.
121
+
122
+ ### Parameter Types: Dials vs Settings
123
+
124
+ The `Synth` class distinguishes between two types of parameters:
125
+
126
+ 1. **Dials** - Real-time controllable parameters that use `pyo.SigTo` for smooth transitions
127
+ 2. **Settings** - Parameters that require rebuilding the synthesis graph when changed
128
+
129
+ By default, all parameters are treated as dials. You can specify which parameters should be dials or settings using the decorator syntax:
130
+
131
+ ```python
132
+ from pyo import LFO, Adsr, Sine
133
+ from hum.pyo_util import Synth
134
+ from time import sleep
135
+
136
+ # Note that here we explicitly tell Synth what arguments are "dials" and what are "settings"
137
+ @Synth(dials='freq', settings='waveform attack')
138
+ def simple_waveform_synth(freq=440, attack=0.01, waveform='sine'):
139
+ env = Adsr(attack=attack, decay=0.1, sustain=0.8, release=0.1, dur=0, mul=0.5).play()
140
+ wave = {
141
+ 'sine': Sine,
142
+ 'triangle': lambda freq, mul: LFO(freq=freq, type=3, mul=mul),
143
+ 'square': lambda freq, mul: LFO(freq=freq, type=1, mul=mul),
144
+ }.get(waveform, Sine)
145
+ return wave(freq=freq, mul=env)
146
+ ```
147
+
148
+ In this example:
149
+ - `freq` is a dial - It changes smoothly in real-time
150
+ - `waveform` and `attack` are settings - Changing them rebuilds the synth
151
+
152
+ ### Interactive Control
153
+
154
+ For interactive control in a REPL, you need to explicitly start and stop the synth:
155
+
156
+ ```python
157
+ # Start the synth (begins making sound)
158
+ simple_waveform_synth.start()
159
+
160
+ # Change the frequency
161
+ simple_waveform_synth(freq=440 * 3 / 2) # Change to 660 Hz
162
+ # The sound continues to play, but now at a different frequency
163
+
164
+ # Change multiple parameters at once
165
+ simple_waveform_synth(freq=440, waveform='triangle')
166
+ # Now playing a triangle wave at 440 Hz
167
+
168
+ # Change the waveform and attack time
169
+ simple_waveform_synth(waveform='square', attack=0.5)
170
+ # Note: You won't hear the change in attack time until the next note is played!
171
+
172
+ # Stop the synth when done
173
+ simple_waveform_synth.stop()
174
+ ```
175
+
176
+ Note that when you restart a synth, it retains its last state:
177
+
178
+ ```python
179
+ # Start the synth again - it will use the last parameter values
180
+ simple_waveform_synth.start() # Still has square waveform and attack=0.5
181
+
182
+ # Change back to sine wave
183
+ simple_waveform_synth(waveform='sine') # Note the attack is still 0.5
184
+
185
+ # Stop the synth when done
186
+ simple_waveform_synth.stop()
187
+ ```
188
+
189
+ > **Warning**: Always remember to stop your synths when done to avoid resource issues. Using the context manager approach is recommended for automatic cleanup.
190
+
191
+ ## Precomputed Knob Changes
192
+
193
+ Instead of interactive control, you can also precompute a sequence of parameter changes:
194
+
195
+ ```python
196
+ from pyo import LFO, Adsr, Sine
197
+ from hum.pyo_util import Synth
198
+ from time import sleep
199
+
200
+ @Synth(dials='freq', settings='waveform attack')
201
+ def simple_waveform_synth(freq=440, attack=0.01, waveform='sine'):
202
+ env = Adsr(attack=attack, decay=0.1, sustain=0.8, release=0.1, dur=0, mul=0.5).play()
203
+ wave = {
204
+ 'sine': Sine,
205
+ 'triangle': lambda freq, mul: LFO(freq=freq, type=3, mul=mul),
206
+ 'square': lambda freq, mul: LFO(freq=freq, type=1, mul=mul),
207
+ }.get(waveform, Sine)
208
+ return wave(freq=freq, mul=env)
209
+
210
+ with simple_waveform_synth as s:
211
+ sleep(1) # Play default settings for a second
212
+ s(freq=440 * 3 / 2) # Change to 660 Hz
213
+ sleep(1)
214
+ s(freq=440, waveform='triangle') # Change to triangle wave at 440 Hz
215
+ sleep(0.5) # Shorter wait this time
216
+ s(waveform='square', attack=0.5) # Change to square wave with longer attack
217
+ sleep(2) # Wait a bit longer
218
+ s(waveform='sine') # Change back to sine wave (attack still 0.5)
219
+ sleep(1) # Wait for the final change to be heard
220
+ ```
221
+
222
+ ## Recording and Analyzing Events
223
+
224
+ The `Synth` class automatically records all parameter changes with timestamps:
225
+
226
+ ```python
227
+ # Get the recorded events after playing
228
+ events = simple_waveform_synth.get_recording()
229
+ ```
230
+
231
+ This gives you a list of timestamped parameter changes:
232
+
233
+ ```python
234
+ [
235
+ (0,
236
+ {'freq': {'value': 440, 'time': 0.025, 'mul': 1, 'add': 0},
237
+ 'attack': 0.01,
238
+ 'waveform': 'sine'}),
239
+ (1.0052499771118164, {'freq': 660.0}),
240
+ (2.007974863052368, {'freq': 440, 'waveform': 'triangle'}),
241
+ (2.0084967613220215, {'waveform': 'triangle'}),
242
+ (2.515920877456665, {'waveform': 'square', 'attack': 0.5}),
243
+ (2.518988609313965, {'waveform': 'square', 'attack': 0.5}),
244
+ (4.524500846862793, {'waveform': 'sine'}),
245
+ (4.525563716888428, {'waveform': 'sine'}),
246
+ (5.528840780258179, {})
247
+ ]
248
+ ```
249
+
250
+ You can round the timestamps for better readability:
251
+
252
+ ```python
253
+ from hum.pyo_util import round_event_times
254
+
255
+ events = list(round_event_times(simple_waveform_synth.get_recording(), 0.1))
256
+ ```
257
+
258
+ This gives you a cleaner view:
259
+
260
+ ```python
261
+ [
262
+ (0.0,
263
+ {'freq': {'value': 440, 'time': 0.025, 'mul': 1, 'add': 0},
264
+ 'attack': 0.01,
265
+ 'waveform': 'sine'}),
266
+ (1.0, {'freq': 660.0}),
267
+ (2.0, {'freq': 440, 'waveform': 'triangle'}),
268
+ (2.0, {'waveform': 'triangle'}),
269
+ (2.5, {'waveform': 'square', 'attack': 0.5}),
270
+ (2.5, {'waveform': 'square', 'attack': 0.5}),
271
+ (4.5, {'waveform': 'sine'}),
272
+ (4.5, {'waveform': 'sine'}),
273
+ (5.5, {})
274
+ ]
275
+ ```
276
+
277
+ ## Composing with Event Sequences
278
+
279
+ You can create, edit, or manipulate event sequences directly:
280
+
281
+ ```python
282
+ # Manually define an event sequence
283
+ events = [
284
+ (
285
+ 0.0,
286
+ {
287
+ 'freq': {'value': 440, 'time': 0.025, 'mul': 1, 'add': 0},
288
+ 'attack': 0.01,
289
+ 'waveform': 'sine',
290
+ },
291
+ ),
292
+ (1.0, {'freq': 660.0}),
293
+ (2.0, {'freq': 440, 'waveform': 'triangle'}),
294
+ (2.0, {'waveform': 'triangle'}),
295
+ (2.5, {'waveform': 'square', 'attack': 0.5}),
296
+ (2.5, {'waveform': 'square', 'attack': 0.5}),
297
+ (4.5, {'waveform': 'sine'}),
298
+ (4.5, {'waveform': 'sine'}),
299
+ (5.5, {}),
300
+ ]
301
+ ```
302
+
303
+ ### Replaying Events
304
+
305
+ You can replay any event sequence through a compatible synth:
306
+
307
+ ```python
308
+ @Synth(dials='freq', settings='waveform attack')
309
+ def simple_waveform_synth(freq=440, attack=0.01, waveform='sine'):
310
+ env = Adsr(attack=attack, decay=0.1, sustain=0.8, release=0.1, dur=0, mul=0.5).play()
311
+ wave = {
312
+ 'sine': Sine,
313
+ 'triangle': lambda freq, mul: LFO(freq=freq, type=3, mul=mul),
314
+ 'square': lambda freq, mul: LFO(freq=freq, type=1, mul=mul),
315
+ }.get(waveform, Sine)
316
+ return wave(freq=freq, mul=env)
317
+
318
+ # Replay the event sequence
319
+ simple_waveform_synth.replay_events(events)
320
+ ```
321
+
322
+ ### Rendering Events to Audio
323
+
324
+ You can render events to audio without real-time playback:
325
+
326
+ ```python
327
+ import recode
328
+
329
+ # Render events to WAV format bytes
330
+ wav_bytes = simple_waveform_synth.render_events(events)
331
+
332
+ # Decode the WAV bytes for analysis or saving
333
+ wf, sr = recode.decode_wav_bytes(wav_bytes)
334
+
335
+ # Visualize the waveform
336
+ from hum import disp_wf
337
+ disp_wf(wf, sr)
338
+ ```
339
+
340
+ ## Advanced Features
341
+
342
+ ### ReplayEvents Class
343
+
344
+ The `ReplayEvents` class is a utility for replaying timestamped events with proper timing:
345
+
346
+ ```python
347
+ from hum.pyo_util import ReplayEvents
348
+
349
+ # Get your events, either from a recording or created manually
350
+ events = [
351
+ (0.0, {'freq': {'value': 440, 'time': 0.025, 'mul': 1, 'add': 0}}),
352
+ (1.0, {'freq': 330.0}),
353
+ (2.0, {'freq': 440}),
354
+ (3.0, {})
355
+ ]
356
+
357
+ # Create a replay generator and iterate through it
358
+ for knob_update in ReplayEvents(events):
359
+ print(f"Update: {knob_update}")
360
+ # Do something with each update
361
+ ```
362
+
363
+ The `ReplayEvents` class supports options like:
364
+ - `emit_none`: If True, yields None to simulate time passing
365
+ - `time_scale`: Speed up or slow down playback (e.g., 2.0 for twice as fast)
366
+ - `ensure_sorted`: Sort events by timestamp before playback
367
+
368
+ ### Event Manipulation and Composition
369
+
370
+ You can manipulate event sequences programmatically:
371
+
372
+ ```python
373
+ # Create a modified version by changing timestamps
374
+ faster_events = [(t/2, params) for t, params in events]
375
+
376
+ # Create a reversed sequence
377
+ reversed_events = [(events[-1][0] - t, params) for t, params in events]
378
+
379
+ # Combine sequences by appending
380
+ melody = events + [(t + events[-1][0], params) for t, params in events]
381
+
382
+ # Transpose a sequence by modifying frequency values
383
+ def transpose(events, semitones):
384
+ factor = 2 ** (semitones/12)
385
+ result = []
386
+ for t, params in events:
387
+ new_params = params.copy()
388
+ if 'freq' in new_params:
389
+ if isinstance(new_params['freq'], dict):
390
+ new_params['freq'] = {
391
+ k: v * factor if k == 'value' else v
392
+ for k, v in new_params['freq'].items()
393
+ }
394
+ else:
395
+ new_params['freq'] = new_params['freq'] * factor
396
+ result.append((t, new_params))
397
+ return result
398
+
399
+ # Transpose up a perfect fifth (7 semitones)
400
+ fifth_up = transpose(events, 7)
401
+ ```
402
+
403
+ ### Complex Synthesis Graphs
404
+
405
+ You can create more sophisticated synthesis graphs by combining Pyo objects:
406
+
407
+ ```python
408
+ from pyo import Sine, Delay, Chorus, Harmonizer, MoogLP
409
+
410
+ @Synth(dials='freq cutoff', settings='delay_time num_voices')
411
+ def complex_synth(freq=440, cutoff=2000, delay_time=0.25, num_voices=3):
412
+ # Create a sine oscillator
413
+ osc = Sine(freq=freq, mul=0.3)
414
+
415
+ # Add harmonizer for multiple voices
416
+ harm = Harmonizer(osc, transpo=[0, 7, 12][:num_voices], feedback=0.1)
417
+
418
+ # Add a filter
419
+ filt = MoogLP(harm, freq=cutoff, res=0.3)
420
+
421
+ # etc...
422
+
423
+ ```
424
+
425
+ ## Hooking a Synth to Event Streams
426
+
427
+ You can connect your synths to external event sources like keyboards, sensors, or algorithmic generators. This allows you to create interactive instruments or audio installations.
428
+
429
+ ### Keyboard Control Integration
430
+
431
+ The `keyboard_control.py` module provides a way to connect keyboard events to your synths, creating an interactive musical instrument controlled by your computer keyboard.
432
+
433
+ The module works by:
434
+
435
+ 1. Detecting keyboard events using the `pynput` library
436
+ 2. Mapping keys to synth parameters using a configurable dictionary
437
+ 3. Calling your synth function with the mapped parameters when keys are pressed
438
+ 4. Supporting multiple callback patterns and configuration options
439
+
440
+ ### Command Line Usage
441
+
442
+ The simplest way to try keyboard control is through the command line:
443
+
444
+ ```bash
445
+ python -m hum.examples.keyboard_control \
446
+ --callback "hum.pyo_synths:sine" \
447
+ --arg-mapping '{"q":130.81,"w":146.83,"e":164.81,"r":174.61,"t":196.00,"y":220.00,"u":246.94,"i":261.63,"o":293.66,"p":329.63,"a":261.63,"s":293.66,"d":329.63,"f":349.23,"g":392.00,"h":440.00,"j":493.88,"k":523.25,"l":587.33,"z":523.25,"x":587.33,"c":659.25,"v":698.46,"b":783.99,"n":880.00,"m":987.77}' \
448
+ --debug
449
+ ```
450
+
451
+ This creates a two-octave piano keyboard layout on your QWERTY keyboard, where:
452
+ - The top two rows (Q-P and A-L) form the white keys
453
+ - The bottom row (Z-M) forms the black keys
454
+ - Each key is mapped to a specific frequency in Hz
455
+
456
+ ### Programmatic Usage
457
+
458
+ You can also use the keyboard control module in your own code:
459
+
460
+ ```python
461
+ from hum.examples.keyboard_control import keyboard_reader
462
+ from hum.pyo_synths import sine # A pre-defined sine wave synth
463
+
464
+ # Define a mapping from keys to frequencies
465
+ key_mapping = {
466
+ "a": 261.63, # C4
467
+ "s": 293.66, # D4
468
+ "d": 329.63, # E4
469
+ "f": 349.23, # F4
470
+ "g": 392.00, # G4
471
+ "h": 440.00, # A4
472
+ "j": 493.88, # B4
473
+ "k": 523.25 # C5
474
+ }
475
+
476
+ # Create a keyboard reader with the mapping
477
+ reader = keyboard_reader(
478
+ callback=sine,
479
+ arg_mapping=key_mapping,
480
+ exit_key="escape",
481
+ read_rate=0.1,
482
+ debug=True
483
+ )
484
+
485
+ # Process keyboard events
486
+ for event in reader:
487
+ if event:
488
+ print(f"Key pressed: {event['key']}")
489
+ if event and event['key'] == 'escape':
490
+ break
491
+ ```
492
+
493
+ ### Advanced Mapping
494
+
495
+ You can map keys to complex parameter dictionaries for more control:
496
+
497
+ ```python
498
+ # Map keys to multiple parameters
499
+ advanced_mapping = {
500
+ "a": {"freq": 261.63, "waveform": "sine"},
501
+ "s": {"freq": 293.66, "waveform": "triangle"},
502
+ "d": {"freq": 329.63, "waveform": "square", "attack": 0.2}
503
+ }
504
+
505
+ # Use with a more complex synth
506
+ reader = keyboard_reader(
507
+ callback=simple_waveform_synth,
508
+ arg_mapping=advanced_mapping
509
+ )
510
+ ```
511
+
512
+ ### How It Works Under the Hood
513
+
514
+ The `keyboard_control.py` module:
515
+
516
+ 1. Registers a callback function with the `pynput` library to capture key presses
517
+ 2. Processes the raw key data into a standardized format
518
+ 3. Looks up the key in the mapping dictionary to find associated parameters
519
+ 4. Calls the synth callback in the appropriate way based on its type:
520
+ - If it's a `Synth` instance, uses the `update` method
521
+ - If it's a regular function, calls it with the mapped parameters
522
+ 5. Yields events in a generator pattern for processing in your code
523
+
524
+ This flexible design allows you to use keyboard control with any type of synth function or parameter mapping, making it easy to create interactive audio experiences.
525
+
526
+ ## Use Cases
527
+
528
+ The `Synth` and keyboard control tools can be used for:
529
+
530
+ 1. **Interactive Music Creation** - Build synthesizers and play them with your keyboard
531
+ 2. **Sound Design** - Experiment with different parameters in real-time
532
+ 3. **Education** - Demonstrate audio concepts with interactive examples
533
+ 4. **Algorithmic Composition** - Create and manipulate event sequences programmatically
534
+ 5. **Audio Prototyping** - Quickly test audio ideas before implementing them in other systems
535
+ 6. **Game Audio** - Create dynamic sound effects that respond to game events
536
+ 7. **Installation Art** - Build interactive audio installations
537
+ 8. **Live Performance** - Control audio in real-time for live shows
538
+
539
+ ## Tips and Best Practices
540
+
541
+ 1. **Use Context Managers** - The `with` statement ensures proper cleanup
542
+ 2. **Round Timestamps** - Use `round_event_times` for readable event sequences
543
+ 3. **Resource Management** - Always stop synths when done to free audio resources
544
+ 4. **Separate Concerns** - Use dials for real-time control and settings for structural changes
545
+ 5. **Start Simple** - Build up complexity gradually as you get comfortable with the system
546
+ 6. **Use Generators** - The functional approach to audio processing is powerful and flexible
547
+ 7. **Test with Rendering** - Use `render_events` to test your sequences without real-time playback
548
+ 8. **Documentation** - Document your synth functions with docstrings and examples
549
+
550
+ ## Under the Hood
551
+
552
+ The `Synth` class works by:
553
+ 1. Converting parameters to Pyo's `SigTo` objects for smooth transitions
554
+ 2. Managing a Pyo server for audio processing
555
+ 3. Recording all parameter changes with timestamps
556
+ 4. Managing the underlying synthesis graph rebuilding when necessary
557
+ 5. Handling event serialization and deserialization
558
+
559
+ The `keyboard_control` module:
560
+ 1. Uses non-blocking event detection to capture keystrokes
561
+ 2. Processes key events into a consistent format
562
+ 3. Maps keys to synth parameters using configurable dictionaries
563
+ 4. Handles different types of callback functions adaptively