hum 1.0.1__tar.gz → 1.0.3__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hum
3
- Version: 1.0.1
3
+ Version: 1.0.3
4
4
  Summary: A python synthesizer for creating and manipulating audio signals.
5
5
  Home-page: https://github.com/thorwhalen/hum
6
6
  License: mit
@@ -16,8 +16,12 @@ A python synthesizer for creating and manipulating audio signals.
16
16
 
17
17
  To install: ```pip install hum```
18
18
 
19
- Note: Some functionalities depend on `pyo`, which itself requires some tools
20
- (namely, [portaudio](https://www.portaudio.com/) and [Portmidi](https://github.com/PortMidi/portmidi)) that _may_ have to be installed manually.
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
+
21
25
 
22
26
 
23
27
 
hum-1.0.3/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # hum
2
+
3
+ A python synthesizer for creating and manipulating audio signals.
4
+
5
+ To install: ```pip install hum```
6
+
7
+ Note: Some functionalities depend on [pyo](https://belangeo.github.io/pyo/download.html),
8
+ which itself requires some tools (namely, [portaudio](https://www.portaudio.com/)
9
+ and [Portmidi](https://github.com/PortMidi/portmidi)) that _may_ have to be
10
+ installed manually.
11
+
12
+
13
+
14
+
15
+
@@ -2,7 +2,7 @@
2
2
  Tools to create audio
3
3
  """
4
4
 
5
- from hum.pyo_util import Synth, knob_params, knob_exclude
5
+ from hum.pyo_util import synth, Synth, knob_params, knob_exclude
6
6
  from hum.utils import (
7
7
  plot_wf,
8
8
  disp_wf,
@@ -34,7 +34,7 @@ def example_01_basic_dual_osc():
34
34
  synth.replay_events(events)
35
35
 
36
36
  # ------------------------- get the wav_bytes of this recording --------------------
37
- wav_bytes = synth.render_recording()
37
+ wav_bytes = synth.render_events()
38
38
  assert isinstance(wav_bytes, bytes)
39
39
  assert len(wav_bytes) > 0, "No bytes returned"
40
40
  # verify that the bytes are a valid WAV file
@@ -190,5 +190,5 @@ def example_06_knob_recording_playback():
190
190
  return ButLP(blend, freq=lfo)
191
191
 
192
192
  synth2 = Synth(dual_osc_graph_offline)
193
- wf, sr = synth2.render_recording(control_events, egress=recode.decode_wav_bytes)
193
+ wf, sr = synth2.render_events(control_events, egress=recode.decode_wav_bytes)
194
194
  return wf, sr
@@ -1,6 +1,7 @@
1
1
  """pyo utils"""
2
2
 
3
3
  import os
4
+ from functools import partial
4
5
  import tempfile
5
6
  import inspect
6
7
  from inspect import Signature, Parameter
@@ -345,51 +346,78 @@ def auto_play(obj):
345
346
 
346
347
  class ReplayEvents:
347
348
  """
348
- An iterator that replays a sequence of timestamped knob updates in real-time.
349
+ Replays timestamped knob updates, optionally emitting None or sleeping to simulate
350
+ timing.
349
351
 
350
- This class takes a list of (timestamp, KnobsDict) events and yields
351
- each update at the correct real-time intervals, automatically sleeping
352
- between updates to recreate the original timing.
352
+ Parameters
353
+ ----------
354
+ events : List[Tuple[float, KnobsDict]]
355
+ A list of (timestamp, knob updates) pairs.
356
+ emit_none : bool
357
+ If True, yields None to simulate time passage; if False, uses time.sleep.
358
+ time_scale : float
359
+ Time compression/stretch factor: 2.0 = 2x faster, 0.5 = half speed.
360
+ ensure_sorted : bool
361
+ Whether to sort the events by timestamp.
353
362
 
354
- Usage:
355
- ------
356
- Simply wrap your recorded control events and feed them into play_events:
363
+ Example
364
+ -------
357
365
 
358
- synth.play_events(ReplayEvents(control_events))
366
+ Consider these events:
359
367
 
360
- Why use ReplayEvents?
361
- ----------------------
362
- - Centralizes real-time replay logic.
363
- - Makes it easy to later add speed controls, jitter, filtering, etc.
364
- - Keeps `play_events` clean and flexible.
365
- - Supports a future where playback streams can be manipulated easily.
368
+ >>> events = [
369
+ ... (0.0, {'freq': 220}),
370
+ ... (0.05, {'freq': 330}),
371
+ ... (0.10, {'freq': 440}),
372
+ ... ]
373
+
374
+ >>> list(ReplayEvents(events, time_scale=50.0))
375
+ [{'freq': 220}, {'freq': 330}, {'freq': 440}]
376
+
377
+ That is, we should really get back the same events, without the timestamps.
378
+
379
+ >>> list(ReplayEvents(events, time_scale=10.0))
380
+ [{'freq': 220}, {'freq': 330}, {'freq': 440}]
381
+
382
+ >>> list(ReplayEvents(events, time_scale=10.0)) == list(dict(events).values())
383
+ True
384
+
385
+ The timestamps are used to pace when new events are emitted.
386
+ Note: Usually we'll use time_scale=1.0 (the default), but we use time_scale=50 here
387
+ just to accelerate the tests.
388
+
389
+ The default is to sleep until the next event should be emitted, but you can also
390
+ emulate a real-time sensor reads by setting emit_none=True.
391
+ In this case, the instance will emit `None` if there's no event to emit at that time.
392
+
393
+ >>> list(ReplayEvents(events, emit_none=True, time_scale=2.0)) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
394
+ [{'freq': 220}, None, ...]
366
395
 
367
- Parameters
368
- ----------
369
- control_events : List[Tuple[float, KnobsDict]]
370
- A list of (timestamp, knob updates) pairs.
371
- speed : float
372
- A multiplier for playback speed. 1.0 = normal speed,
373
- 2.0 = twice as fast, 0.5 = half speed, etc. Default is 1.0.
374
396
  """
375
397
 
376
- def __init__(
377
- self, control_events: List[Tuple[float, KnobsDict]], speed: float = 1.0
378
- ):
379
- self.control_events = control_events
380
- self.speed = speed
398
+ def __init__(self, events, *, emit_none=True, time_scale=1.0, ensure_sorted=False):
399
+ if ensure_sorted:
400
+ if not events:
401
+ raise ValueError("Events list must not be empty.")
402
+ self.events = sorted(events, key=lambda x: x[0])
403
+ else:
404
+ self.events = events
405
+ self.emit_none = emit_none
406
+ self.time_scale = time_scale
381
407
 
382
- def __iter__(self) -> Iterator[Union[KnobsDict, None]]:
383
- if not self.control_events:
384
- return
385
- base_time, first_update = self.control_events[0]
386
- yield first_update
387
- for (curr_time, updates), (next_time, _) in zip(
388
- self.control_events, self.control_events[1:]
389
- ):
390
- sleep_duration = (next_time - curr_time) / self.speed
391
- time.sleep(max(sleep_duration, 0))
392
- yield updates
408
+ def __iter__(self):
409
+ prev_time = self.events[0][0]
410
+ for timestamp, knobs in self.events:
411
+ delay = (timestamp - prev_time) / self.time_scale
412
+ if self.emit_none:
413
+ steps = int(delay / 0.01)
414
+ for _ in range(steps):
415
+ yield None
416
+ else:
417
+ if delay > 0:
418
+ time.sleep(delay)
419
+ yield knobs
420
+ prev_time = timestamp
393
421
 
394
422
 
395
423
  def list_if_string(x):
@@ -479,8 +507,8 @@ class Synth(MutableMapping):
479
507
  synth_func, "_knob_params", set(self._synth_func_params)
480
508
  )
481
509
  _knob_params = list_if_string(_knob_params)
482
- _knob_exclude = knob_exclude or getattr(synth_func, "_knob_exclude", set())
483
510
  knob_exclude = list_if_string(knob_exclude)
511
+ _knob_exclude = knob_exclude or getattr(synth_func, "_knob_exclude", set())
484
512
  self._knob_params = set(_knob_params) - set(_knob_exclude)
485
513
  self._knob_defaults = {k: self._synth_func_params[k] for k in _knob_params}
486
514
  self._live_params = set(self._knob_params)
@@ -716,45 +744,9 @@ class Synth(MutableMapping):
716
744
  if self._record_on_start:
717
745
  self.stop_recording()
718
746
 
719
- def play_events(
720
- self,
721
- events: Iterator[Union[KnobsDict, None]],
722
- *,
723
- idle_sleep_time=0.01,
724
- inter_event_delay=0,
725
- tail_time=1.0,
726
- ):
727
- """
728
- Play an event stream, applying updates from an iterator of KnobsDicts or None.
729
-
730
- Parameters
731
- ----------
732
- events : Iterator[Union[KnobsDict, None]]
733
- An iterator yielding KnobsDict updates (or None for idle).
734
- tail_time : float
735
- Time to wait after finishing event playback to allow sound to finish.
736
- idle_sleep_time : float
737
- Time to sleep if the iterator yields None (idle).
738
- inter_event_delay : float
739
- Time to sleep systematically after each non-None event.
740
- """
741
- with self:
742
- for event in events:
743
- if event is None:
744
- time.sleep(idle_sleep_time)
745
- continue
746
-
747
- self.update(event)
748
-
749
- if inter_event_delay > 0:
750
- time.sleep(inter_event_delay)
751
-
752
- time.sleep(tail_time)
753
-
754
- def replay_events(self, control_events, *, tail_time=1.0):
755
- self.play_events(ReplayEvents(control_events), tail_time=tail_time)
747
+ # Rendering events (playing recordings etc.) --------------------------------------
756
748
 
757
- def render_recording(
749
+ def render_events(
758
750
  self,
759
751
  control_events=None,
760
752
  *,
@@ -763,7 +755,7 @@ class Synth(MutableMapping):
763
755
  file_format="wav",
764
756
  suffix_buffer_seconds=0.0,
765
757
  ):
766
- """Render the recording to a file or return it processed by the egress function."""
758
+ """Render the control events to an audio file or return it via an egress function."""
767
759
  if not control_events:
768
760
  control_events = self.get_recording()
769
761
  if not control_events:
@@ -783,25 +775,12 @@ class Synth(MutableMapping):
783
775
  synth_output = self._synth_func(**raw_params).out()
784
776
  table_recorder = TableRec(synth_output, table=table).play()
785
777
 
786
- try:
787
- for i, (event_time, updates) in enumerate(normalized):
788
- next_time = (
789
- normalized[i + 1][TIME_IDX]
790
- if i + 1 < len(normalized)
791
- else total_duration
792
- )
793
- dur = next_time - event_time
794
-
795
- for key, val in updates.items():
796
- if isinstance(val, dict):
797
- for attr in ["value", "time", "mul", "add"]:
798
- if attr in val:
799
- setattr(raw_params[key], attr, val[attr])
800
- else:
801
- raw_params[key].value = val
778
+ def delay_func(dur):
779
+ server.recordOptions(dur=dur)
780
+ server.start()
802
781
 
803
- server.recordOptions(dur=dur)
804
- server.start()
782
+ try:
783
+ self._apply_event_sequence(normalized, delay_func, raw_params=raw_params)
805
784
  finally:
806
785
  table_recorder.stop()
807
786
 
@@ -823,6 +802,85 @@ class Synth(MutableMapping):
823
802
  else:
824
803
  raise ValueError("Invalid egress")
825
804
 
805
+ def play_events(
806
+ self,
807
+ events: Union[Iterator[Union[KnobsDict, None]], List[Tuple[float, KnobsDict]]],
808
+ *,
809
+ idle_sleep_time=0.01,
810
+ inter_event_delay=0,
811
+ tail_time=1.0,
812
+ ):
813
+ """
814
+ Play an event stream, applying updates from either:
815
+ - an iterator yielding KnobsDicts or None (real-time stream), or
816
+ - a list of (timestamp, KnobsDict) pairs (automatically wrapped).
817
+ """
818
+ # Auto-wrap if we detect a list of (timestamp, KnobsDict) format
819
+ if isinstance(events, list) and events and isinstance(events[0], tuple):
820
+ ts, ev = events[0]
821
+ if isinstance(ts, (int, float)) and isinstance(ev, dict):
822
+ events = ReplayEvents(events)
823
+
824
+ filtered_events = []
825
+ curr_time = 0.0
826
+ for e in events:
827
+ if e is not None:
828
+ filtered_events.append((curr_time, e))
829
+ curr_time += inter_event_delay
830
+ else:
831
+ time.sleep(idle_sleep_time)
832
+
833
+ def delay_func(dur):
834
+ time.sleep(dur)
835
+
836
+ with self:
837
+ self._apply_event_sequence(filtered_events, delay_func)
838
+ time.sleep(tail_time)
839
+
840
+ def replay_events(self, control_events, *, tail_time=1.0):
841
+ self.play_events(ReplayEvents(control_events), tail_time=tail_time)
842
+
843
+ def _apply_event_sequence(self, events, delay_func, raw_params=None):
844
+ """
845
+ Apply a sequence of events using a delay function.
846
+
847
+ Parameters
848
+ ----------
849
+ events : Iterable[Tuple[float, KnobsDict]]
850
+ Timestamped knob updates.
851
+ delay_func : Callable[[float], None]
852
+ Function to call to delay between events (e.g., time.sleep or offline record trigger).
853
+ raw_params : Optional[Dict[str, SigTo]]
854
+ If provided, updates will be applied to this dict instead of self.knobs.
855
+ """
856
+ if not events:
857
+ return
858
+
859
+ TIME_IDX = 0
860
+ base_time = events[0][TIME_IDX]
861
+ normalized = [(t - base_time, knobs) for t, knobs in events]
862
+
863
+ for i, (event_time, updates) in enumerate(normalized):
864
+ next_time = normalized[i + 1][TIME_IDX] if i + 1 < len(normalized) else None
865
+ dur = next_time - event_time if next_time is not None else None
866
+
867
+ for key, val in updates.items():
868
+ target = raw_params[key] if raw_params else self.knobs[key]
869
+ if isinstance(target, SigTo):
870
+ if isinstance(val, dict):
871
+ for attr in ["value", "time", "mul", "add"]:
872
+ if attr in val:
873
+ setattr(target, attr, val[attr])
874
+ else:
875
+ target.value = val
876
+ elif raw_params is None:
877
+ self.knobs[key] = val
878
+
879
+ if dur is not None:
880
+ delay_func(dur)
881
+
882
+ # Context manager support ---------------------------------------------------------
883
+
826
884
  def __del__(self):
827
885
  if self._server is not None:
828
886
  self._server.stop()
@@ -834,6 +892,24 @@ class Synth(MutableMapping):
834
892
  def __exit__(self, exc_type, exc_value, traceback):
835
893
  self.stop()
836
894
 
895
+ # Handling the decorator mechanisms -----------------------------------------------
896
+
897
+ def __new__(cls, synth_func=None, **kwargs):
898
+ # Case 1: Used directly as @Synth
899
+ if synth_func is not None and callable(synth_func):
900
+ instance = super().__new__(cls)
901
+ instance.__init__(synth_func, **kwargs)
902
+ return instance
903
+ # Case 2: Used with config as @Synth(knob_params=...)
904
+ else:
905
+
906
+ def decorator(func):
907
+ return cls(func, **kwargs)
908
+
909
+ return decorator
910
+
911
+ # MutableMapping interface --------------------------------------------------------
912
+
837
913
  @property
838
914
  def __signature__(self):
839
915
  return Signature(
@@ -861,23 +937,24 @@ class Synth(MutableMapping):
861
937
  return f"<Synth {list(self.knobs.keys())}>"
862
938
 
863
939
 
864
- # --------------------------------------------------------------------------------------
865
- # Example functions for testing the Synth class
866
- # --------------------------------------------------------------------------------------
867
-
868
-
869
- def basic_synth_test():
870
- def simple_sine(freq=220, volume=1):
871
- sine = Sine(freq=freq, mul=volume)
872
-
873
- synth = Synth(simple_sine)
874
-
875
- with synth:
876
- time.sleep(1)
877
- synth["freq"] = 220 * 3 / 2
878
- time.sleep(1)
879
- synth["freq"] = 220 * 2
880
- time.sleep(1)
881
-
882
- events = synth.get_recording()
883
- synth.replay_events(events)
940
+ def synth(
941
+ synth_func=None,
942
+ *,
943
+ knob_params: Optional[Set[str]] = None,
944
+ knob_exclude: Optional[Set[str]] = None,
945
+ sr=DFLT_PYO_SR,
946
+ nchnls=DFLT_PYO_NCHNLS,
947
+ record_on_start: bool = True,
948
+ event_log_factory: RecordFactory = list, # No argument factory that makes an Appendable
949
+ audio="portaudio",
950
+ verbosity=DFLT_PYO_VERBOSITY,
951
+ **server_kwargs,
952
+ ):
953
+ synth_kwargs = dict(
954
+ {k: v for k, v in locals().items() if k not in {"synth_func", "server_kwargs"}},
955
+ **server_kwargs,
956
+ )
957
+ if synth_func is None:
958
+ return partial(Synth, **synth_kwargs)
959
+ else:
960
+ return Synth(synth_func, **synth_kwargs)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hum
3
- Version: 1.0.1
3
+ Version: 1.0.3
4
4
  Summary: A python synthesizer for creating and manipulating audio signals.
5
5
  Home-page: https://github.com/thorwhalen/hum
6
6
  License: mit
@@ -16,8 +16,12 @@ A python synthesizer for creating and manipulating audio signals.
16
16
 
17
17
  To install: ```pip install hum```
18
18
 
19
- Note: Some functionalities depend on `pyo`, which itself requires some tools
20
- (namely, [portaudio](https://www.portaudio.com/) and [Portmidi](https://github.com/PortMidi/portmidi)) that _may_ have to be installed manually.
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
+
21
25
 
22
26
 
23
27
 
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = hum
3
- version = 1.0.1
3
+ version = 1.0.3
4
4
  url = https://github.com/thorwhalen/hum
5
5
  platforms = any
6
6
  description_file = README.md
hum-1.0.1/README.md DELETED
@@ -1,11 +0,0 @@
1
- # hum
2
-
3
- A python synthesizer for creating and manipulating audio signals.
4
-
5
- To install: ```pip install hum```
6
-
7
- Note: Some functionalities depend on `pyo`, which itself requires some tools
8
- (namely, [portaudio](https://www.portaudio.com/) and [Portmidi](https://github.com/PortMidi/portmidi)) that _may_ have to be installed manually.
9
-
10
-
11
-
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes