-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrelic_keymanager.py
1047 lines (846 loc) · 36.7 KB
/
relic_keymanager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2024 Cooper Dalrymple
#
# SPDX-License-Identifier: MIT
"""
`relic_keymanager`
================================================================================
Tools to manage notes in musical applications. Includes note priority, arpeggiation, and sequencing.
* Author(s): Cooper Dalrymple
Implementation Notes
--------------------
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://circuitpython.org/downloads
* Adafruit's SimpleMath library: https://github.com/adafruit/Adafruit_CircuitPython_SimpleMath
"""
# imports
__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/relic-se/CircuitPython_KeyManager.git"
import asyncio
import random
import time
from micropython import const
try:
from typing import Callable
from circuitpython_typing.io import ROValueIO
except ImportError:
pass
class KeyState:
"""An enum-like class representing states used by :class:`Key` and :class:`Keyboard`."""
NONE: int = const(0)
"""Indicates that the key hasn't been activated in any way"""
PRESS: int = const(1)
"""Indicates that the key has been pressed"""
RELEASE: int = const(2)
"""Indicates that the key has been released"""
class Key:
"""An abstract layer to interface with the :class:`Keyboard` class."""
def __init__(self):
pass
@property
def state(self) -> int:
"""The current state as a constant value of :class:`KeyState`."""
return KeyState.NONE
@property
def velocity(self) -> float:
"""Get the current velocity (0.0-1.0)."""
return 1.0
class DebouncerKey(Key):
"""An abstract layer to debouncer sensor input to use physical key objects with the
:class:`Keyboard` class. The Adafruit-CircuitPython-Debouncer module must be installed to use
this class, else a ImportError will be thrown upon instantiation.
:param io_or_predicate: The input pin or arbitrary predicate to debounce
:int inverted: Whether or not to invert the state of the input. When invert is `False`, the
signal is active-high. When it is `True`, the signal is active-low.
"""
def __init__(self, io_or_predicate: ROValueIO | Callable[[], bool], inverted: bool = False):
from adafruit_debouncer import Debouncer
self._debouncer = Debouncer(io_or_predicate)
self._inverted = inverted
inverted: bool = False
"""Whether or not the state is inverted. When invert is `False`, the signal is active-high. When
it is `True`, the signal is active-low.
"""
@property
def state(self) -> int:
"""The current state as a constant value of :class:`KeyState`. When accessed, the input pin
or arbitraary predicate will be updated with basic debouncing.
"""
self._debouncer.update()
if self._debouncer.rose:
return KeyState.PRESS if not self._inverted else KeyState.RELEASE
elif self._debouncer.fell:
return KeyState.RELEASE if not self._inverted else KeyState.PRESS
else:
return KeyState.NONE
class Note:
"""Object which represents the parameters of a note. Contains note number, velocity, key number
(if evoked by a :class:`Key` object), and timestamp of when the note was created.
:param notenum: The MIDI note number representing the frequency of a note.
:param velocity: The strength of which a note was pressed from 0.0 to 1.0.
:param keynum: The index number of the :class:`Key` object which created this :class:`Note`
object.
"""
def __init__(self, notenum: int, velocity: float = 1.0, keynum: int = None):
self.notenum = notenum
self.velocity = velocity
self.keynum = keynum
self.timestamp = time.monotonic()
notenum: int = None
"""The MIDI note number representing the frequency of a note."""
velocity: float = 1.0
"""The strength of which a note was pressed from 0.0 to 1.0."""
keynum: int = None
"""The index number of the :class:`Key` object which created this :class:`Note` object."""
@property
def data(self) -> tuple[int, float, int]:
"""Return all note data as tuple. The data is formatted as: (notenum:int, velocity:float,
keynum:int). Keynum may be set as `None` if not applicable.
"""
return (self.notenum, self.velocity, self.keynum)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.notenum == other.notenum
elif isinstance(other, Voice):
return self.notenum == other.note.notenum if not other.note is None else False
elif type(other) == int:
return self.notenum == other
elif type(other) == list:
for i in other:
if self.__eq__(i):
return True
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return self.notenum != other.notenum
elif isinstance(other, Voice):
return self.notenum != other.note.notenum if not other.note is None else True
elif type(other) == int:
return self.notenum != other
elif type(other) == list:
for i in other:
if not self.__ne__(i):
return False
return True
else:
return False
def __lt__(self, other):
if isinstance(other, self.__class__):
return self.notenum < other.notenum
elif type(other) == int:
return self.notenum < other
else:
return False
def __gt__(self, other):
if isinstance(other, self.__class__):
return self.notenum > other.notenum
elif type(other) == int:
return self.notenum > other
else:
return False
def __le__(self, other):
if isinstance(other, self.__class__):
return self.notenum <= other.notenum
elif type(other) == int:
return self.notenum <= other
else:
return False
def __ge__(self, other):
if isinstance(other, self.__class__):
return self.notenum >= other.notenum
elif type(other) == int:
return self.notenum >= other
else:
return False
class Voice:
"""Object which represents the parameters of a :class:`Keyboard` voice. Used to allocate
:class:`Note` objects to a pre-defined number of available slots in a logical manner based on
timing and keyboard mode.
:param index: The position of the voice in the pre-defined set of keyboard voices.
"""
def __init__(self, index: int):
self.index = index
self.time = time.monotonic()
index: int = None
"""The position of the voice in the pre-defined set of keyboard voices."""
time: float = None
"""The last time in seconds at which a note was registered with this voice."""
_note: Note = None
@property
def note(self) -> Note:
"""The :class:`Note` object assigned to this voice. When a note is assigned to a voice, the
voice is "active" until the note is cleared by setting it to `None`.
"""
return self._note
@note.setter
def note(self, value: Note) -> None:
self._note = value
if not value is None:
self.time = time.monotonic()
@property
def active(self) -> bool:
"""The active state of the voice. Will return `True` if a note has been assigned to this
voice.
"""
return not self.note is None
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.index == other.index
elif isinstance(other, Note) or type(other) == list:
return self.note == other
elif type(other) is int:
return self.index == other # NOTE: Use index or notenum?
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return self.index != other.index
elif isinstance(other, Note) or type(other) == list:
return self.note != other
elif type(other) is int:
return self.index != other # NOTE: Use index or notenum?
else:
return False
class TimerStep:
"""An enum-like class representing common step divisions."""
WHOLE: float = 0.25
"""Whole note beat division"""
HALF: float = 0.5
"""Half note beat division"""
QUARTER: float = 1.0
"""Quarter note beat division"""
DOTTED_QUARTER: float = 1.5
"""Dotted quarter note beat division"""
EIGHTH: float = 2.0
"""Eighth note beat division"""
TRIPLET: float = 3.0
"""Triplet note beat division"""
SIXTEENTH: float = 4.0
"""Sixteenth note beat division"""
THIRTYSECOND: float = 8.0
"""Thirtysecond note beat division"""
class Timer:
"""An abstract class to help handle timing functionality of the :class:`Arpeggiator` and
:class:`Sequencer` classes. Note press and release timing is managed by bpm (beats per minute),
steps (divisions of a beat), and gate (note duration during step).
:param bpm: The beats per minute of timer.
:param steps: The number of steps to divide a single beat. The minimum value allowed is 0.25, or
a whole note.
:param gate: The duration of each pressed note per step to play before releasing as a ratio from
0.0 to 1.0.
"""
def __init__(self, bpm: float = 120.0, steps: float = TimerStep.EIGHTH, gate: float = 0.5):
self._reset(False)
self.gate = gate
self.bpm = bpm
self.steps = steps
def _update_timing(self) -> None:
self._step_time = 60.0 / self._bpm / self._steps
self._gate_duration = self._gate * self._step_time
def _reset(self, immediate=True):
self._now = time.monotonic()
if immediate:
self._now -= self._step_time
_bpm: float = 120.0
@property
def bpm(self) -> float:
"""Beats per minute."""
return self._bpm
@bpm.setter
def bpm(self, value: float) -> None:
self._bpm = max(value, 1.0)
self._update_timing()
_steps: float = TimerStep.EIGHTH
@property
def steps(self) -> float:
"""The number of steps per beat (or the beat division). The minimum value allowed is 0.25,
or a whole note. The pre-defined :class:`TimerStep` constants can be used here.
"""
return self._steps
@steps.setter
def steps(self, value: float) -> None:
self._steps = max(value, TimerStep.WHOLE)
self._update_timing()
_gate: float = 0.5
@property
def gate(self) -> float:
"""The duration each pressed note per step will play before releasing within a step of a
beat as a ratio of that step from 0.0 to 1.0.
"""
return self._gate
@gate.setter
def gate(self, value: float) -> None:
self._gate = min(max(value, 0.0), 1.0)
self._update_timing()
_active: bool = False
@property
def active(self) -> bool:
"""Whether or not the timer object is enabled (running)."""
return self._active
@active.setter
def active(self, value: bool) -> None:
if value == self._active:
return
self._active = value
if self._active:
self._now = time.monotonic() - self._step_time
else:
self._do_release()
if self.on_enabled:
self.on_enabled(self._active)
on_enabled: Callable[[bool], None] = None
"""The callback method that is called when :attr:`active` is changed. Must have 1 parameter for
the current active state. Ie: :code:`def enabled(active):`
"""
on_step: Callable[[], None] = None
"""The callback method that is called when a step is triggered. This callback will fire whether
or not the step has pressed any notes. However, any pressed notes will occur before this
callback is called.
"""
on_press: Callable[[int, float], None] = None
"""The callback method that is called when a timed step note is pressed. Must have 2 parameters
for note value and velocity (0.0-1.0). Ie: :code:`def press(notenum, velocity):`.
"""
on_release: Callable[[int], None] = None
"""The callback method that is called when a timed step note is released. Must have 1 parameter
for note value. Velocity is always assumed to be 0.0. Ie: :code:`def release(notenum):`.
"""
_last_press: list[int] = []
async def update(self):
"""Update the timer object and call any relevant callbacks if a new beat step or the end of
the gate of a step is reached. The actual functionality of this method will depend on the
child class that utilizes the :class:`Timer` parent class.
"""
while True:
if not self._active:
await self._sleep(0.01)
continue
self._update()
self._do_step()
if self._last_press:
await self._sleep(self._gate_duration)
self._do_release()
await self._sleep(self._step_time - self._gate_duration)
else:
await self._sleep(self._step_time)
async def _sleep(self, delay: float):
self._now += delay
await asyncio.sleep(self._now - time.monotonic())
def _update(self):
pass
def _do_step(self):
if callable(self.on_step):
self.on_step()
def _do_press(self, notenum, velocity):
if callable(self.on_press):
self.on_press(notenum, velocity)
self._last_press.append(notenum)
def _do_release(self):
if callable(self.on_release) and self._last_press:
for notenum in self._last_press:
self.on_release(notenum)
self._last_press.clear()
class ArpeggiatorMode:
"""An enum-like class containing constaints for the possible modes of the :class:`Arpeggiator`
class.
"""
UP: int = const(0)
"""Play notes based on ascending note value."""
DOWN: int = const(1)
"""Play notes based on descending note value."""
UPDOWN: int = const(2)
"""Play notes based on note value in ascending order then descending order. The topmost and
bottommost notes will not be repeated.
"""
DOWNUP: int = const(3)
"""Play notes based on note value in descending order then ascending order. The topmost and
bottommost notes will not be repeated.
"""
PLAYED: int = const(4)
"""Play notes based on the time at which they were played (ascending)."""
RANDOM: int = const(5)
"""Play notes in a random order."""
class Arpeggiator(Timer):
"""Use this class to iterate over notes based on time parameters. Note press and release timing
is managed by bpm (beats per minute), steps (divisions of a beat), and gate (note duration
during step).
:param bpm: The beats per minute of timer.
:param steps: The number of steps to divide a single beat. The minimum value allowed is 0.25, or
a whole note.
:param gate: The duration of each pressed note per step to play before releasing as a ratio from
0.0 to 1.0.
:param mode: The method of stepping through notes as specified by :class:`ArpeggiatorMode`
constants.
"""
def __init__(
self, bpm: float = 120.0, steps: float = TimerStep.EIGHTH, mode: int = ArpeggiatorMode.UP
):
Timer.__init__(
self,
bpm=bpm,
steps=steps,
)
self.mode = mode
_pos: int = 0
def _reset(self, immediate=True):
Timer._reset(self, immediate)
self._pos = 0
_octaves: int = 0
@property
def octaves(self) -> int:
"""The number of octaves in which to extend the notes, either up or down."""
return self._octaves
@octaves.setter
def octaves(self, value: int) -> None:
self._octaves = value
if self._notes:
self.notes = self._raw_notes
_probability: float = 1.0
@property
def probability(self) -> float:
"""The likeliness that a note will be played within a step, ranging from 0.0 (never) to 1.0
(always).
"""
return self._probability
@probability.setter
def probability(self, value: float) -> None:
self._probability = min(max(value, 0.0), 1.0)
_mode: int = ArpeggiatorMode.UP
@property
def mode(self) -> int:
"""The method of stepping through notes. See :class:`ArpeggiatorMode` for options."""
return self._mode
@mode.setter
def mode(self, value: int) -> None:
self._mode = value % 6
if self._notes:
self.notes = self._raw_notes
_raw_notes: list[Note] = []
_notes: list[Note] = []
def _get_notes(self, notes: list[Note] = []):
if not notes:
return notes
if abs(self._octaves) > 0:
l = len(notes)
for octave in range(1, abs(self._octaves) + 1):
for i in range(0, l):
notes.append(
Note(
notes[i].notenum + octave * (-1 if self._octaves < 0 else 1) * 12,
notes[i].velocity,
)
)
if self._mode == ArpeggiatorMode.UP:
notes.sort()
elif self._mode == ArpeggiatorMode.DOWN:
notes.sort(reverse=True)
elif self._mode == ArpeggiatorMode.UPDOWN:
notes.sort()
if len(notes) > 2:
_notes = notes[1:-1].copy()
_notes.reverse()
notes = notes + _notes
elif self._mode == ArpeggiatorMode.DOWNUP:
notes.sort(reverse=True)
if len(notes) > 2:
_notes = notes[1:-1].copy()
_notes.reverse()
notes = notes + _notes
# PLAYED = notes stay as is, RANDOM = index is randomized on update
return notes
@property
def notes(self) -> list[Note]:
"""The :class:`Note` objects which the arpeggiator is currently stepping through ordered as
specified by :attr:`mode` and affected by :attr:`octaves`.
"""
return self._notes
@notes.setter
def notes(self, value: list[Note]) -> None:
if not self._notes:
self._reset()
self._raw_notes = value.copy()
self._notes = self._get_notes(value)
def _update(self):
if self._notes:
if self._probability < 1.0 and (
self._probability == 0.0 or random.random() > self._probability
):
return
if self.mode == ArpeggiatorMode.RANDOM:
self._pos = random.randrange(0, len(self._notes), 1)
else:
self._pos = (self._pos + 1) % len(self._notes)
self._do_press(self._notes[self._pos].notenum, self._notes[self._pos].velocity)
class Sequencer(Timer):
"""Sequence notes using the :class:`Timer` class to create a multi-track note sequencer. By
default, the Sequencer is set up for a single 4/4 measure of 16 notes with one track. Each note
of each track can be assigned any note value and velocity. The length and number of tracks can
be reassigned during runtime.
:param length: The number of steps of each track. The minimum value allowed is 1.
:param tracks: The number of tracks to create and sequence. The minimum value allowed is 1.
:param bpm: The beats per minute of the timer.
"""
def __init__(self, length: int = 16, tracks: int = 1, bpm: float = 120.0):
Timer.__init__(self, bpm=bpm, steps=TimerStep.SIXTEENTH)
self.length = length
self.tracks = tracks
self._data = [[None for j in range(self._length)] for i in range(self._tracks)]
_data: list = None
_length: int = 16
@property
def length(self) -> int:
"""The number of steps for each track. If the length is shortened, all of the step data
beyond the new length will be deleted, and if the sequencer is also currently running, it
should loop back around automatically to the start of the track data. The minimum allowed
is 1.
"""
return self._length
@length.setter
def length(self, value: int) -> None:
value = max(value, 1)
if self._data:
if value > self._length:
for i in range(self._tracks):
self._data[i] = self._data[i] + [None for j in range(value - self._length)]
elif value < self._length:
for i in range(self._tracks):
del self._data[i][value:]
self._length = value
_tracks: int = 1
@property
def tracks(self) -> int:
"""The number of note tracks to sequence. If the number of tracks is shortened, the tracks
at an index greater to or equal than the number will be deleted. If a larger number of
tracks is provided, the newly created tracks will be empty. The minimum allowed is 1.
"""
return self._tracks
@tracks.setter
def tracks(self, value: int) -> None:
value = max(value, 1)
if self._data:
if value > self._tracks:
self._data = self._data + [
[None for j in range(self._length)] for i in range(value - self._tracks)
]
elif value < self._tracks:
del self._data[value:]
self._tracks = value
_pos: int = 0
@property
def position(self) -> int:
"""The current position of the sequencer within the track length (0-based)."""
return self._pos
def set_note(self, position: int, notenum: int, velocity: float = 1.0, track: int = 0) -> None:
"""Set the note value and velocity of a track at a specific step index.
:param position: Index of the step (0-based). Will be limited to the track length.
:param notenum: Value of the note.
:param velocity: Velocity of the note (0.0-1.0).
:param track: Index of the track (0-based). Will be limited to the track count.
"""
track = min(max(track, 0), self._tracks)
position = min(max(position, 0), self._length)
self._data[track][position] = (notenum, velocity)
def get_note(self, position: int, track: int = 0) -> tuple[int, int]:
"""Get the note data for a specified track and step position. If a note isn't defined at
specific index, a value of `None` will be returned.
:param position: Index of the step (0-based). Will be limited to the track length.
:param track: Index of the track (0-based). Will be limited to the track count.
:return: note data (notenum, velocity)
"""
track = min(max(track, 0), self._tracks)
position = min(max(position, 0), self._length)
return self._data[track][position]
def has_note(self, position: int, track: int = 0) -> bool:
"""Check whether or note a specific step within a track has been set with note data.
:param position: Index of the step (0-based). Will be limited to the track length.
:param track: Index of the track (0-based). Will be limited to the track count.
:return: if the track step has a note
"""
return not self.get_note(position, track) is None
def remove_note(self, position: int, track: int = 0) -> None:
"""Remove the note data as a specific step within a track.
:param position: Index of the step (0-based). Will be limited to the track length.
:param track: Index of the track (0-based). Will be limited to the track count.
"""
track = min(max(track, 0), self._tracks)
position = min(max(position, 0), self._length)
self._data[track][position] = None
def get_track(self, track=0) -> list[tuple[int, int]]:
"""Get list of note data for a specified track index (0-based). If the track isn't
available, a value of `None` will be returned.
:return: track data list of note tuples as (notenum, velocity)
"""
return self._data[min(max(track, 0), self._tracks)]
on_step: Callable[[int], None] = None
"""The callback method that is called when a step is triggered. This callback will fire whether
or not the step has any notes. However, any pressed notes will occur before this callback is
called. Must have 1 parameter for sequencer position index. Ie: :code:`def step(pos):`.
"""
def _update(self):
self._pos = (self._pos + 1) % self._length
for i in range(self._tracks):
note = self._data[i][self._pos]
if note and note[0] > 0 and note[1] > 0:
self._do_press(note[0], note[1])
def _do_step(self):
if callable(self.on_step):
self.on_step(self._pos)
class KeyboardMode:
"""An enum-like class representing Keyboard note handling modes."""
HIGH: int = const(0)
"""When the keyboard is set as this mode, it will prioritize the highest note value."""
LOW: int = const(1)
"""When the keyboard is set as this mode, it will prioritize the lowest note value."""
LAST: int = const(2)
"""When the keyboard is set as this mode, it will prioritize notes by the order in when they
were played/appended.
"""
class Keyboard:
"""Manage notes, voice allocation, arpeggiator assignment, sustain, and relevant callbacks using
this class.
:param keys: A list of :class:`Key` objects which will be used to update the keyboard state.
:param max_voices: The maximum number of voices/notes to be played at once.
:param root: Set the base note number of the physical key inputs.
"""
def __init__(
self,
keys: tuple[Key] = [],
max_voices: int = 1,
root: int = 48,
mode: int = KeyboardMode.HIGH,
):
self.root = root
self._keys = keys
self.mode = mode
self.max_voices = max_voices
self._voices = [Voice(i) for i in range(self.max_voices)]
on_voice_press: Callable[[Voice], None] = None
"""The callback method to be called when a voice is pressed. Must have 1 parameter for the
:class:`Voice` object. Ie: :code:`def press(voice):`.
"""
on_voice_release: Callable[[Voice], None] = None
"""The callback method to be called when a voice is released. Must have 1 parameter for the
:class:`Voice` object. Velocity is always assumed to be 0.0. Ie: :code:`def release(voice):`.
"""
on_key_press: Callable[[int, int, float], None] = None
"""The callback method to be called when a :class:`Key` object is pressed. Must have 3
parameters for keynum, note value, velocity (0.0-1.0), and keynum. Ie: :code:`def press(keynum,
notenum, velocity):`.
"""
on_key_release: Callable[[int, int], None] = None
"""The callback method to be called when a :class:`Key` object is released. Must have 2
parameters for keynum and note value. Velocity is always assumed to be 0.0. Ie: :code:`def
release(keynum, notenum):`.
"""
_keys: tuple[Key] = None
@property
def keys(self) -> tuple[Key]:
"""The :class:`Key` objects which will be used to update the keyboard state."""
return self._keys
_arpeggiator: Arpeggiator = None
@property
def arpeggiator(self) -> Arpeggiator:
"""The :class:`Arpeggiator` object assigned to the keyboard."""
return self._arpeggiator
@arpeggiator.setter
def arpeggiator(self, value: Arpeggiator) -> None:
if self._arpeggiator:
self._arpeggiator.on_enabled = None
self._arpeggiator.on_press = None
self._arpeggiator.on_release = None
self._arpeggiator = value
self._arpeggiator.on_enabled = self._timer_enabled
self._arpeggiator.on_press = self._timer_press
self._arpeggiator.on_release = self._timer_release
_mode: int = KeyboardMode.HIGH
@property
def mode(self) -> int:
"""The note allocation mode. Use one of the mode constants of :class:`KeyboardMode`. Note
allocation won't be updated until the next update call.
"""
return self._mode
@mode.setter
def mode(self, value: int) -> None:
self._mode = value % 3
_sustain: bool = False
_sustained: list[Note] = []
@property
def sustain(self) -> bool:
"""Whether or not the notes pressed are sustained after being released until this property
is set to `False`.
"""
return self._sustain
@sustain.setter
def sustain(self, value: bool) -> None:
if value != self._sustain:
self._sustain = value
self._sustained = self._notes.copy() if self._sustain else []
self._update()
_notes: list[Note] = []
@property
def all_notes(self) -> list[Note]:
"""All active :class:`Note` objects."""
return self._notes + self._sustained
@property
def notes(self) -> list[Note]:
"""Active :class:`Notes` objects according to the current :class:`KeyboardMode`."""
notes = self.all_notes
if self._mode in {KeyboardMode.HIGH, KeyboardMode.LOW}:
notes.sort(reverse=(self._mode == KeyboardMode.HIGH))
else: # KeyboardMode.LAST
notes.sort(key=lambda note: note.timestamp)
return notes[: self._max_voices]
def append(self, notenum: int | Note, velocity: float = 1.0, keynum: int = None):
"""Add a note to the keyboard buffer. Useful when working with MIDI input or another note
source. Any previous notes with the same notenum value will be removed automatically.
:param notenum: The number of the note. Can be defined by MIDI notes, a designated sample
index, etc. When using MODE_HIGH or MODE_LOW, the value of this parameter will affect
the order. A :class:`Note` object can be used instead of providing notenum, velocity,
and keynum parameters directly.
:param velocity: The velocity of the note from 0.0 through 1.0.
:param keynum: An additional index reference typically used to associate the note with a
physical :class:`Key` object. Not required for use of the keyboard.
"""
self.remove(notenum, True)
note = notenum if isinstance(notenum, Note) else Note(notenum, velocity, keynum)
self._notes.append(note)
if self._sustain:
self._sustained.append(note)
self._update()
def remove(self, notenum: int | Note, remove_sustained: bool = False):
"""Remove a note from the keyboard buffer. Useful when working with MIDI input or another
note source. If the note is found (and the keyboard isn't being sustained or
remove_sustained is set as `True`), the release callback will trigger automatically
regardless of the `update` parameter.
:param notenum: The value of the note that you would like to be removed. All notes in the
buffer with this value will be removed. Can be defined by MIDI note value, a designated
sample index, etc. Can also use a :class:`Note` object instead.
:param remove_sustained: Whether or not you would like to override the current sustained
state of the keyboard and release any notes that are being sustained.
"""
if not notenum in self.all_notes:
return
self._notes = [note for note in self._notes if note != notenum]
if remove_sustained and self._sustain and self._sustained:
self._sustained = [note for note in self._sustained if note != notenum]
self._update()
async def update(self, delay: float = 0.01) -> None:
"""Update :attr:`keys` objects if they were provided during initialization.
:param delay: The amount of time to sleep between polling in seconds.
"""
while self._keys:
for i in range(len(self._keys)):
state = self._keys[i].state
if state == KeyState.NONE:
continue
notenum = self.root + i
if state == KeyState.PRESS:
velocity = self._keys[i].velocity
self.append(notenum, velocity, i)
if callable(self.on_key_press):
self.on_key_press(i, notenum, velocity)
else: # KeyState.RELEASE
self.remove(notenum)
if callable(self.on_key_release):
self.on_key_release(i, notenum)
await asyncio.sleep(delay)
def _update(self) -> None:
if not self._arpeggiator or not self._arpeggiator.active:
self._update_voices(self.notes)
else:
self._arpeggiator.notes = self.all_notes
# Callbacks for arpeggiator
def _timer_enabled(self, active: bool) -> None:
if active:
self.arpeggiator.notes = self.all_notes
else:
self.update()
def _timer_press(self, notenum: int, velocity: float) -> None:
self._update_voices([Note(notenum, velocity)])
def _timer_release(self, notenum: int) -> None: # NOTE: notenum is ignored
self._update_voices()
_voices: list[Voice] = []
@property
def voices(self) -> list[Voice]:
"""The :class:`Voice` objects used by the :class:`Keyboard` object."""
return self._voices
_max_voices: int = 1
@property
def max_voices(self) -> int:
"""The maximum number of voices used by this keyboard to allocate notes. Must be greater
than 1. When this property is set, it will automatically release and delete any voices or
add new voice objects depending on the previous number of voices. Any voice related
callbacks may be triggered during this process.
"""
return self._max_voices
@max_voices.setter
def max_voices(self, value: int) -> None:
self._max_voices = max(value, 1)
if len(self._voices) > self._max_voices:
for i in range(len(self._voices) - 1, self._max_voices - 1, -1):
self._release_voice(self._voices[i])
del self._voices[i]
elif len(self._voices) < self._max_voices:
for i in range(len(self._voices), self._max_voices):
self._voices.append(Voice(i))
self._update_voices()
@property
def active_voices(self) -> list[Voice]:
"""All keyboard voices that are "active", have been assigned a note. The voices will
automatically be sorted by the time they were last assigned a note from oldest to newest.
"""
voices = [voice for voice in self._voices if voice.active]
voices.sort(key=lambda voice: voice.time)
return voices
@property
def inactive_voices(self) -> list[Voice]:
"""All keyboard voices that are "inactive", do not currently have a note assigned. The
voices will automatically be sorted by the time they were last assigned a note from oldest
to newest.
"""
voices = [voice for voice in self._voices if not voice.active]
voices.sort(key=lambda voice: voice.time)
return voices