-
Notifications
You must be signed in to change notification settings - Fork 0
/
midi.py
2029 lines (1713 loc) · 60.5 KB
/
midi.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
#!/usr/bin/python
# -*- coding: utf8 -*-
from __future__ import print_function
import rtmidi
import itertools, collections
import time
import random
from fractions import Fraction
from util2 import lispy_funcall, is_listy
import signal, sys
from pprint import pprint as pp
import copy
DURATION = .2
VELOCITY = 100
VERBOSE = False
SHOW_NOTES_OFFSET = 0
def debug_log(*args):
if VERBOSE:
print(*args)
def close_midi_handler(signal, frame):
global midiout
del midiout
sys.exit(0)
def install_close_handler():
signal.signal(signal.SIGINT, close_midi_handler)
def sleep(dur, show_notes=None):
if show_notes is None: show_notes = SHOW_NOTES
if show_notes:
NOTE_DISPLAYER.show_accumulated_notes()
dur = get_dur(dur)
time.sleep(dur)
# I kept the option of a verbose `sleep()` function so that I could see the
# music outputted to the screen:
def verbose_sleep(dur):
try: sleep.ticks
except: sleep.ticks = 0
if sleep.ticks % 64 == 0:
print('------------------')
elif sleep.ticks % 32 == 0:
print('---------------')
elif sleep.ticks % 16 == 0:
print('------------')
elif sleep.ticks % 8 == 0:
print('---------')
elif sleep.ticks % 4 == 0:
print('------')
else:
print('---')
sleep.ticks += 1
dur = get_dur(dur)
time.sleep(dur)
'''
So now if I wanted verbose timing output all I have to do is:
'''
# sleep = verbose_sleep
def verbose_sleep_6_8(dur):
try: sleep.ticks
except: sleep.ticks = 0
if sleep.ticks % 48 == 0:
print('------------------')
elif sleep.ticks % 24 == 0:
print('---------------')
elif sleep.ticks % 12 == 0:
print('------------')
elif sleep.ticks % 6 == 0:
print('---------')
elif sleep.ticks % 2 == 0:
print('------')
else:
print('---')
sleep.ticks += 1
dur = get_dur(dur)
time.sleep(dur)
#sleep = verbose_sleep_6_8
'''
#todo #fixme - get rid of all the adhoc '-' comparisons, try to use do_hold_note
#todo #fixme - currently ',' and "'" will stop the last note, let it hold
#todo do some stuff with the Russian Doll chord concept - C -> Am -> F -> Dm etc
'''
def midi_init():
global midiout
midiout = rtmidi.MidiOut()
available_ports = midiout.get_ports()
if available_ports:
midiout.open_port(0)
else:
print("No midi port available, opening virtual port")
midiout.open_virtual_port("My virtual output")
return midiout
midi_init()
def is_special_val(pitch):
return pitch in (None,'','-',',',"'")
def is_silent(pitch):
if is_special_val(pitch):
return True
elif isinstance(pitch, Silent):
return True
else:
return False
def do_hold_note(new_note): # decide whether to hold existing note
return new_note in [None,'-',',',"'"]
'low-level midi message functionality'
def midi_note_on(pitch, vel, chan=0):
control = [0x90 + chan, pitch, vel]
midiout.send_message(control)
def midi_note_off(pitch, chan=0):
control = [0x80 + chan, pitch, 0]
midiout.send_message(control)
def midi_panic():
for i in range(127):
for ch in range(16):
midi_note_off(i, chan=ch)
def midi_program_change(instrument_no, chan=0):
control = [0xc0 + chan, instrument_no]
midiout.send_message(control)
panic = midi_panic
prog_chg = midi_program_change
#todo clear the notes on KeyboardInterrupt or something
class NoteDisplayer:
def __init__(self):
self.notes = set()
self.prev_notes = set()
# accumulate positions before printing a line of notes
# (allowing multiple zipped events generators to be properly displayed
def start_note(self, note_pos, chan):
note = (note_pos,chan)
self.notes.add(note)
# allow rearticulation by not considering it a "held note"
# (remove from prev_notes)
self.prev_notes.discard(note)
def release_note(self, note_pos, chan):
note = (note_pos,chan)
self.notes.discard(note)
def show_accumulated_notes(self):
#todo do I really need the list() conversion?
held_notes = self.prev_notes.intersection(self.notes)
notes = list(
self.notes - held_notes
)
#print('notes',self.notes)
#print('prev',self.prev_notes)
#print('held',held_notes)
held_note_positions = {n[0] for n in held_notes}
print(
show_notes_spatially(
notes, list(held_note_positions),
SHOW_NOTES_OFFSET, SHOW_NOTE_NAMES,
)
)
self.prev_notes = self.notes
self.notes = copy.copy(self.notes)
SHOW_NOTES = True
SHOW_NOTE_NAMES = True
NOTE_DISPLAYER = NoteDisplayer()
'higher level functionality - octave offset & some rest / note holding logic'
def note_on(n, vel=VELOCITY, oct=4, chan=0, show_notes=SHOW_NOTES):
pitch = up(n, oct*12)
if not is_silent(pitch):
midi_note_on(pitch, vel, chan=chan)
if show_notes:
NOTE_DISPLAYER.start_note(pitch, chan)
def note_off(n, oct=4, chan=0, show_notes=SHOW_NOTES):
pitch = up(n, oct*12)
if not is_silent(pitch): # if the pitch was silent, no need to silence
midi_note_off(pitch, chan=chan)
if show_notes:
NOTE_DISPLAYER.release_note(pitch, chan)
def rand_inst(chan=0):
instrument = random.randint(0,127)
midi_program_change(instrument, chan=chan)
return instrument
def play(ns, dur=DURATION, vel=VELOCITY, oct=4, leave_sounding=False, chan=0):
if dur is None: dur = DURATION
playe(
ev_pitches(
ns, vel=vel, oct=oct, dur=dur,
leave_sounding=leave_sounding, chan=chan
)
)
def chord_on(ns, vel=VELOCITY, oct=4, chan=0, show_notes=None):
return playe(
ev_chord_on(
ns, vel=vel, oct=oct,
chan=chan, show_notes=show_notes
)
)
def chord_off(ns, oct=4, chan=0, show_notes=None):
return playe(
ev_chord_off(ns, oct=oct, chan=chan, show_notes=show_notes)
)
def chordstrn_on(chordstrn, vel=VELOCITY, oct=4, chan=0, show_notes=None):
return playe(
ev_chordstrn_on(
chordstrn, vel=vel, oct=oct,
chan=chan, show_notes=show_notes
)
)
def chordstrn_off(chordstrn, oct=4, chan=0, show_notes=None):
return playe(
chordstrn_off(chordstrn, oct=oct, chan=chan, show_notes=show_notes)
)
def chordname_on(chordname, vel=VELOCITY, oct=4, chan=0, show_notes=None):
return playe(
ev_chordname_on(chordname, vel=vel, oct=oct, chan=chan, show_notes=show_notes)
)
def chordname_off(chordname, oct=4, chan=0, show_notes=None):
return playe(
ev_chordname_off(chordname, oct=oct, chan=chan, show_notes=show_notes)
)
def ev_chord_on(ns, vel=VELOCITY, oct=4, chan=0, show_notes=None):
if show_notes is None: show_notes = SHOW_NOTES
if ns:
for n in ns:
yield ('note_on', n, vel, oct, chan, show_notes)
def ev_chord_off(ns, oct=4, chan=0, show_notes=None):
if show_notes is None: show_notes = SHOW_NOTES
if ns:
for n in ns:
yield ('note_off', n, oct, chan, show_notes)
def ev_chordstrn_on(chordstrn, vel=VELOCITY, oct=4, chan=0, show_notes=None):
if show_notes is None: show_notes = SHOW_NOTES
if chordstrn:
pitches = strn2pitches(chordstrn)
for e in ev_chord_on(
pitches, vel=vel, oct=oct, chan=chan, show_notes=show_notes
):
yield e
def ev_chordstrn_off(chordstrn, oct=4, chan=0, show_notes=None):
if show_notes is None: show_notes = SHOW_NOTES
if chordstrn:
pitches = strn2pitches(chordstrn)
for e in ev_chord_off(
pitches, oct=oct, chan=chan, show_notes=show_notes
):
yield e
def ev_chordname_on(chordname, vel=VELOCITY, oct=4, chan=0, show_notes=None):
if show_notes is None: show_notes = SHOW_NOTES
if chordname:
if chordname in chordtxt:
chordstrn = chordtxt[chordname]
for e in ev_chordstrn_on(
chordstrn, vel=vel, oct=oct, chan=chan, show_notes=show_notes
):
yield e
def ev_chordname_off(chordname, oct=4, chan=0, show_notes=None):
if show_notes is None: show_notes = SHOW_NOTES
if chordname:
if chordname in chordtxt:
chordstrn = chordtxt[chordname]
for e in ev_chordstrn_off(
chordstrn, oct=oct, chan=chan, show_notes=show_notes
):
yield e
def chord(ns, dur=.2, vel=VELOCITY, oct=4):
chord_on(ns, vel, oct)
sleep(dur)
chord_off(ns, oct)
'''
I became interested in having a more general function
that would turn a note or chord on. If you provided just
a single note, it would turn the note on, but if you
provided a whole list/iterable, it would put all the
notes on as a chord:
'''
def notec_on(item, vel=VELOCITY, oct=4, chan=0):
if item in (None,''): return
if isinstance(item,list) or isinstance(item,tuple):
chord_on(item, vel, oct, chan=chan)
else:
note_on(item, vel, oct, chan=chan)
def notes_on_g(item, vel=VELOCITY, oct=4, chan=0, show_notes=None):
if show_notes is None: show_notes = SHOW_NOTES
if item in (None,''): yield None
if isinstance(item,list) or isinstance(item,tuple):
for note in item:
yield ('note_on', note, vel, oct, chan, show_notes)
else:
yield ('note_on', item, vel, oct, chan, show_notes)
'''
And similarly, a `notec_off` function
that handles either a note or a whole chord:
'''
def notec_off(item, oct=4):
if item in (None,''): return
if isinstance(item,list) or isinstance(item,tuple):
chord_off(item, oct)
else:
note_off(item, oct)
'''
Fun with Music Theory: adding Scales
------------------------------------
I added some different kinds of scales:
'''
scales = {
'major' : [0,2,4,5,7,9,11],
'lydian': [0,2,4,6,7,9,11],
'minor' : [0,2,3,5,7,8,10],
'dorian': [0,2,3,5,7,9,10],
'harmonic minor': [0,2,3,5,7,8,11],
'melodic minor' : [0,2,3,5,7,9,11],
}
chords = {
'major': (0,4,7),
'minor': (0,3,7),
'diminished': (0,3,6),
'diminished 7': (0,3,6,9),
'major 7': (0,4,7,11),
'minor 7': (0,3,7,10),
'minor 6': (0,3,7,9),
'minor major 7': (0,3,6,11),
'half-diminished 7': (0,3,6,10),
}
'''
Then I made a function that would extend each scale
by adding several additional octaves
'''
def extend_scales(num_octs=4):
for scale_type, scale in scales.items():
scale += [n + 12*oct for oct in range(1,num_octs) for n in scale]
scale += [scale[0]+12*num_octs]
def get_scale(scale_type_or_scale):
if isinstance(scale_type_or_scale, str):
return scales[scale_type_or_scale]
else:
return scale_type_or_scale
'scale ascending and descending'
def ev_scale(scale, dur=DURATION, omit_last=False, leave_sounding=False):
'scale can be a scale_type or a scale itself'
scale = get_scale(scale)
'ascending'
for e in ev_pitches(scale, dur=dur, leave_sounding=leave_sounding):
yield e
'descending'
if omit_last:
desc_scale = scale[-2:0:-1]
else:
desc_scale = scale[-2::-1]
for e in ev_pitches(desc_scale, dur=dur, leave_sounding=leave_sounding):
yield e
def play_scale(scale, dur=DURATION, omit_last=False):
playe(
ev_scale(scale, dur, omit_last)
)
def choose_some_scales():
return random.sample(scales.keys(), 2)
def play_scales(dur=DURATION):
my_scales = choose_some_scales()
for i,scale_type in enumerate(my_scales):
print(scale_type)
is_last = True if i == len(my_scales) - 1 else False
omit_last = False if is_last else True
play_scale(scale_type, omit_last=omit_last)
triad_scale_offsets = (0,2,4)
def scale_triad(scale, offs, invert=False):
pat = triad_scale_offsets
if invert: pat = tuple(-i for i in pat)
return tuple(scale[offs + i] for i in pat)
def scale_triads(scale, num_octs=2, omit_last=False):
scale = get_scale(scale)
'ascending'
ascending_range = range(7*num_octs + 1)
for i in ascending_range:
yield scale_triad(scale, i)
'descending'
if omit_last: descending_range = range(7*num_octs - 1, 0, -1)
else: descending_range = range(7*num_octs - 1, -1, -1)
for i in descending_range:
yield scale_triad(scale, i)
def play_scales_triads(num_octs=2, dur=.2, leave_sounding=True):
my_scales = choose_some_scales()
for i,scale_type in enumerate(my_scales):
print('triads from the ' + scale_type + ' scale')
is_last = True if i == len(my_scales) - 1 else False
omit_last = False if is_last else True
play(
scale_triads(scale_type, num_octs, omit_last=omit_last),
leave_sounding=leave_sounding
)
def scale_broken_triads(scale, num_octs=1, offs=7, dur=DURATION):
scale = get_scale(scale)
# ascending
for i in range(7*num_octs):
for j in scale_triad(scale, i+offs):
yield j
# descending
for i in range(7*num_octs, -1, -1):
for j in reversed(scale_triad(scale, i+offs)):
yield j
def play_scales_broken_triads(num_octs=1, offs=7, dur=DURATION):
for scale_type,scale in scales.items():
print('triads from the ' + scale_type + ' scale')
play(
scale_broken_triads(scale_type, num_octs=num_octs, offs=offs, dur=dur),
leave_sounding=False
)
chord(scale_triad(scale, 0), dur=2)
def init_music_theory():
extend_scales()
init_music_theory()
'-- Tue Feb 24 2015 --'
def up(pitch,amt): # transpose up
if is_special_val(pitch): return pitch
elif isinstance(pitch,list) or isinstance(pitch,collections.Iterable):
return (up(p, amt) for p in pitch)
else: return pitch + amt
def get_dur(dur):
if dur is None:
return DURATION
elif callable(dur): # allow a function to be used for duration
return dur()
else:
return dur
def swung_dur(long_dur=.4, short_dur=.2): #-- 06-01-15
return icycle((long_dur, short_dur))
def swung_dur2(long_dur=.2, short_dur=.1):
return icycle((long_dur, long_dur, short_dur, short_dur))
def play_swung(notes_gen):
play(notes_gen, swung_dur().next) #todo #test, it said next() and I changed it
def rand(): # can be passed as duration for a random "wind chimes" effect
amt = float(random.randint(1,50)) / 40
return amt
#note play() leaves notes followed by '-' sounding for some reason.
#todo allow play() to leave a note followed by '-' playing but then still turn it off when it's done
'''
* #todo make a function that takes an ev_pitches and filters out all the notes_off events
'''
def remove_note_offs(events):
for event in events:
pass #todo
# with Rowan, allowed None to be passed to notec_on
cool_lick = iter([0,3,None,0,5,None,0,3,None,0,0,0,-2,0,0,0])
part2 = iter([3,7,None,3,9,None,9,7,None,3,5,7,None,5,3,None])
cool_lick_harm = iter([[0,3],[3,7],None,[0,3],[5,9],None,[0,9],[3,7],None,[0,3],[0,5],[0,7],-2,[0,5],[0,3],0])
cool_lick2 = [up(n,24) for n in[None,None,None,None,7,None,12,None,8,None,5,7,None,5,7,7]]
def play_cool_lick(dur=.2):
cool_lick = [0,3,None,0,5,None,0,3,None,0,0,0,-2,0,0,0]*16
play(cool_lick)
def play_cool_lick2_high(dur=.2):
play(cool_lick2)
melody = itertools.cycle([1,2,3,4])
def play_1234_melody():
play(melody)
def play_forever(lick_gen, dur=.2):
play(itertools.cycle(lick_gen), dur=dur)
'''
cool_lick = iter([0,3,None,0,5,None,0,3,None,0,0,0,-2,0,0,0])
part2 = iter([3,7,None,3,9,None,9,7,None,3,5,7,None,5,3,None])
cool_lick_harm = iter([[0,3],[3,7],None,[0,3],[5,9],None,[0,9],[3,7],None,[0,3],[0,5],[0,7],-2,[0,5],[0,3],0])
'''
def combine(part1_gen,part2_gen):
#todo #fixme: am I really using this or am I using izip?
# lists don't work
# xranges don't work either
while True:
x,y = (part1_gen.next(), part2_gen.next())
if x is None or x is StopIteration:
yield y
elif y is None or y is StopIteration:
yield x
else:
yield (x,y)
if x is StopIteration and y is StopIteration:
break
# example of combining parts and looping forever with a generator
part_i = iter([0,2,None,4,None,0,0,None,2])
part_j = iter([4,5,None,7,None,4,4,None,5])
ij4ever = itertools.izip(itertools.cycle(part_i), itertools.cycle(part_j))
izip = itertools.izip_longest
icycle = itertools.cycle
ichain = itertools.chain.from_iterable
lchain = lambda x: list(ichain(x))
dbl = lambda L: lchain([i,i] for i in L)
def sweet_groove():
play_forever(izip(cool_lick, cool_lick2, part2))
#todo allow '-' to mean "hold previous pitches over"
#todo allow ' ' to mean "stop previous note"
#todo allow a Case Octave Shift to happen after a ' ': e.g. 'm-g-a-b-e-B-c-d--- B-emg-d-s-emgab---', the B should go Down
'-- Mon Apr 6 2015 --'
def two_hands(parts):
return izip(parts['rh'],parts['lh'])
bach5bars = [
{
'rh': up([ '-','-', 3, 2, 3, '-', 5, '-', 7,'-','-','-', 8,'-','-','-' ],12),
'lh': [ 3,'-',-9,'-','-','-', '-','-','-', 15, 14, 15, 12, 14, 10, 12 ],
},
{
'rh': up([ '-','-', 5, 3, 5, '-', 7, '-', 8,'-','-','-', 10,'-','-','-' ],12),
'lh': [ 8, 12,10,12, 8, 10, 7, 8, 5, 15, 14, 12, 14, 15, 12, 14 ],
},
{
'rh': up([ 7,'-',12,'-', 10,'-', 8,'-', 7, 8,10, 8, 7,'-', 5,'-' ],12),
'lh': [ 3, 15,14, 12, 14, 15,12, 14, 10,15,14,12,10, 12, 8, 10 ],
},
{
'rh': up([ 3,'-', 7,'-', 10,'-', 15,'-','-', 12,14,15,17,'-',15,'-' ],12),
'lh': [ 7, 12,10, 8, 7, 8, 5, 7, 0, 10, 9, 7, 9, 10, 7, 9 ],
},
]
bach9bars = [
{ # Fm | Bbm
'rh': up([ 12, 10, 8, 7, 8, '-', 5,'-', 13,'-','-','-' ],12),
'lh': [ -7,'-', 5,'-','-', 7, 8, 7, 5, 3, 1, 0 ],
},
{ # Gm7b5 | C7
'rh': up([ '-', 12,10, 9, 10, '-', 7,'-', 16,'-','-','-' ],12),
'lh': [ -2,'-', 7,'-','-', 8, 10, 8, 7, 5, 4, 2 ],
},
{ # C7
'rh': up([ '-', 17,19,20, 22, '-',19, 16, 13,'-', 12,'-' ],12),
'lh': [ 0, 2, 4, 5, 7, 8,10, 7, 5, 4, 5, 4 ],
},
{ # Fm sus | Fm
'rh': up([ 10, 8, 7, 8, 10,13,12, 10, 8, 7, 5, 4 ],12),
'lh': [ 5,'-','-','-', '-', 0, 2, 4, 5, 7, 8,10 ],
},
{ # Fm | Bbm
'rh': up([ -4,'-', 5,'-','-', 7, 8, 7, 5, 3, 1, 0 ],24),
'lh': [ 12, 10, 8, 7, 8, '-', 5,'-', 13,'-','-','-' ],
},
{ # Gm7b5 | C7
'rh': up([ -2,'-', 7,'-','-', 8, 10, 8, 7, 5, 4, 2 ],24),
'lh': [ '-', 12,10, 9, 10, '-', 7,'-', 16,'-','-','-' ],
},
{ # C7
'rh': up([ 0, 2, 4, 5, 7, 8,10, 7, 5, 4, 5, 4 ],24),
'lh': [ '-', 17,19,20, 22, '-',19, 16, 13,'-', 12,'-' ],
},
{ # Fm sus | Fm
'rh': up([ 5,'-', 0, '-', '-', -2, -4, -5, -7,-8,-4,-5 ],24),
'lh': [ 10, 8, 7, 8, 10, 13, 12, 10, 8, 7, 5, 4 ],
},
{ # Fm
'rh': up([ 12, 10,8, 7, 8,'-', 5,'-', 20, '-','-','-'],12),
'lh': [ 8,'-',5,'-', '-', 7, 8, 7, 5, 3, 1, 0],
},
{ # Bo7
'rh': up([ '-', 19,17, 16, 17,'-',14,'-', 11,'-','-','-'],12),
'lh': [ -1,'-', 8,'-', '-', 7, 5, 3, 2, 0, -1, -3],
},
{ # G7
'rh': up([ '-',12,14,15, 17,'-',14,11, 8,'-',7,'-'],12),
'lh': [ -5,-3,-1, 0, 2, 3, 5, 2, 0, -1,0, -1],
},
{ # Cm
'rh': up([ '-', 5, 3, 2, 3,'-', 0,'-', 15,'-','-','-'],12),
'lh': [ 3,'-',12,'-', '-', 14,15, 14, 12, 10, 9, 7],
},
]
'''
{ # F#o7
'rh': up([],12),
'lh': [],
},
{ # D7
'rh': up([],12),
'lh': [],
},
{ # G7 | Cm
'rh': up([],12),
'lh': [],
},
{ # Fm | G7
'rh': up([],12),
'lh': [],
},
{ # Cm | Fm
'rh': up([],12),
'lh': [],
},
{ # Dm7b5 | G7
'rh': up([],12),
'lh': [],
},
{ # G7
'rh': up([],12),
'lh': [],
},
{ # Cm sus | Cm
'rh': up([],12),
'lh': [],
},
{ # F7
'rh': up([],12),
'lh': [],
},
{ # Bbm
'rh': up([],12),
'lh': [],
},
'''
def consolidate_bars(both_hands_bars):
return {
'rh': list(itertools.chain(*[b['rh'] for b in both_hands_bars])),
'lh': list(itertools.chain(*[b['lh'] for b in both_hands_bars])),
}
def play_piece(piece):
play(two_hands(consolidate_bars(piece)))
# e.g. play_piece(bach9bars) - #todo #fixme - this seems to note hold out '-' notes
'-- Sun May 3 2015 --'
note_name_str = 'crdsefmgoahbCRDSEFMGOAHB'
note_names = {k:v for k,v in enumerate(note_name_str)}
note_numbers = {
'c':0, 'i':0,
'j':1, 'r':1,
'd':2, 'y':2, 'z':2,
'k':3, 's':3,
'e':4, 't':4,
'f':5, 'l':5,
'm':6, 'u':6,
'g':7, 'v':7,
'o':8, 'n':8,
'a':9, 'w':9, 'x':9,
'h':10, 'p':10,
'b':11, 'q':11,
'C':12, 'I':12,
'J':13, 'R':13,
'D':14, 'D':14, 'Y':14, 'Z':14,
'S':15, 'K':15,
'E':16, 'T':16,
'F':17, 'L':17,
'M':18, 'U':18,
'G':19, 'V':19,
'O':20, 'N':20,
'A':21, 'W':21, 'X':21,
'H':22, 'P':22,
'Q':23, 'B':23,
}
#note_numbers = {v:k for k,v in note_names.items()}
#note_names = {v:k for k,v in note_numbers.items()}
note_names[None] = ' '
note_numbers[' '] = None
# reflexive keys: these are all "themselves"
note_names['-'] = '-' # hold prev note
note_numbers['-'] = '-'
note_names['_'] = '_' # play note down an octave from prev
note_numbers['_'] = '_'
note_names[','] = ',' # silently go down an octave
note_numbers[','] = ','
note_names["'"] = "'" # silently go up an octave
note_numbers["'"] = "'"
def note_name(pitch_num):
if pitch_num is None:
return ' '
else:
return note_names[pitch_num % 24]
'-- Sun May 31 2015 --'
def note_diff(note1,note2):
#print 'note_diff({note1},{note2})'.format(note1=note1,note2=note2)
if note1 == None or note2 == None \
or note1 == '-' or note2 == '-':
#print ' returning None'
return None
else:
#print ' returning ', (note2-note1)
return note2-note1
def abs_note_diff(note1,note2):
diff = note_diff(note1,note2)
if diff is not None:
return abs(diff)
else:
return None
BIG_OFFSET = 12
def subtract_24_til_close_enough(prev, n):
#print ' subtract_24_til_close_enough(', prev, n, ')'
while note_diff(prev,n) > BIG_OFFSET:
n -= 24
#print ' -= 24 =', n
#print ' returning', n
return n
def add_24_til_close_enough(prev, n):
#print ' add_24_til_close_enough(', prev, n, ')'
while note_diff(prev,n) <= -BIG_OFFSET:
n += 24
#print ' += 24 =', n
#print ' returning', n
return n
def int_or_self(x): # int() won't allow param None, nor can return it
if isinstance(x, object) and hasattr(x, '__int__'):
return int(x)
else:
return x
class Silent(object):
'''used to allow "'" and "," to go up and down an octave without making a sound'''
def __init__(self, note):
self.note = int(note) # don't let note be itself a Silent()
def __repr__(self):
val = repr(self.note)
return 'Silent(' + val + ')'
def __int__(self):
return self.note
def __add__(self, i):
return Silent(int(self) + int(i))
def __radd__(self, i):
return self.__add__(i)
def __sub__(self, i):
return Silent(int(self) - int(i))
def __rsub__(self, i):
return Silent(int(i) - int(self))
def __abs__(self):
return Silent(abs(int(self)))
def __neg__(self): # unary -
return Silent(-int(self))
def __cmp__(self, i):
return cmp(int_or_self(self), int_or_self(i))
def __rcmp__(self, i):
return cmp(int_or_self(i), int_or_self(self))
def close_1_big_interval(n, prev):
if n == '_': # "_" goes down an octave
n = prev - 12
elif n == ',': # silently go down an octave
n = Silent(prev - 12)
elif n == "'": # silently go up an octave
n = Silent(prev + 12)
else: # figure out what octave to play the next note
diff = abs_note_diff(prev,n)
if diff >= BIG_OFFSET:
#todo #fixme - this following comparison has weird values in it sometimes like None and ''! seems to work tho
if n > prev: # going up?
n = subtract_24_til_close_enough(prev, n) # go down instead
else: # going down?
n = add_24_til_close_enough(prev, n) # go up instead
return n
def close_big_intervals(nums, prev_pitch=None):
'''
change octaves to close up any gaps bigger than say an octave
used by strn2pitches to allow the octave-wrapping letter case semantics
'''
for n in nums:
n = close_1_big_interval(n, prev_pitch)
yield n
if n not in ['-',' ',None]: prev_pitch = n
def close_big_intervals_interactive(prev_pitch = None):
'just like close_big_intervals but you have to .send it the nums and you instantly get the next yield'
n = None
while True:
n = yield n
if n is None: return
n = close_1_big_interval(n, prev_pitch)
#todo #fixme should this next line be above?
if n not in ['-',' ']: prev_pitch = n
def strn2numbers(strn):
return (note_numbers[ch] for ch in strn)
def strn2pitches(strn, prev_pitch=None):
return close_big_intervals(strn2numbers(strn), prev_pitch)
def ev_strn(strn, dur=DURATION, leave_sounding=False,
show_notes=None, prev_pitch=None,
vel=VELOCITY, oct=4, chan=0,
):
global SHOW_NOTES
if show_notes is None: show_notes = SHOW_NOTES
return ev_pitches(
strn2pitches(strn, prev_pitch),
dur=dur, vel=vel, oct=oct, chan=chan,
leave_sounding=leave_sounding,
show_notes=show_notes,
)
def play_strn(strn, dur=DURATION, leave_sounding=False,
show_notes=None, prev_pitch=None,
vel=VELOCITY, oct=4):
if show_notes is None: show_notes = SHOW_NOTES
if strn is None:
return None
else:
# playe returns the last pitch for continuity with subsequent melodies
return playe(
ev_strn(strn,
dur=dur,
leave_sounding=leave_sounding,
show_notes=show_notes,
prev_pitch=prev_pitch,
vel=vel,
oct=oct,
)
)
estrn = ev_strn
pstrn = play_strn
def strn_note_on(ch):
pitch = note_numbers[ch]
note_on(pitch)
'-- Mon Jun 1 2015 --'
def wind_chimes():
while True:
strn = raw_input('> ')
play_strn(strn, rand)
nostalgic_arp_melody = 'cdefgegCECEGcGcedAFAFDaDafdfdAFA'
nostalgic_accomp = 'e-e--egfe-e--egef-d---A---D--- '
def play_nostalgic_arp_melody():
play_strn(nostalgic_arp_melody * 2)
play_strns([nostalgic_arp_melody * 2, nostalgic_accomp], octaves=[0,2])
# Bach Invention 4 in Dm
bach4strn = [
"defgahrhagfef-a-D-g-R-E-DEFGAHRHAGFEFDEFGAhAGFEDECDEFGaGFEDCDEFDEFg-----CDECDEf---h---a-g-Chagfefgagfgf-C-C-CDCDCDCDCDCDCDCDCDChagfeCdemgahagfedhcdefgabCDEFoFEDCbCbDCbaoaomedcdemoadCbaomemoabCmEDCbaoabCDEaFEDCbAOMEA--EC-baa--ahCdChagahgahCDeDChaga-FEF-g-E- DEFGAHRHAGFEF-D-g--DREaRDbR--DDChagfh-rdefgaDf-edd-----------",
"------------defgahrhagfef-a-D-e-g-R-d-D-f-g-a-h-c-C-e-f-g-a-hgahCDeDChagafgahCdChagfecdefgAgfedcdHc-_-FGAHcdEdcHAGAHcdefGfedcHAHcAHcM-----GAHGAHE-----F-f-d-B-O-E-AOABcdefefefefefefefefefefefefefefefe-E-D-C-b-a-D-E-F-D-E-_-a_HcdsMsdcHAG--GAHC-G-c-fgabRDeDRbagf-a-D-e-g-R-defgahrhagfefga-_-H--cHAG'hagfefga-_-D-----------",
]
bach6strn = [
" E---S---D---R---b---a---o---m---oao-bab-omo-ese---m---o---a---b---R---S---E-S-R-b-E---_-------'-O---E---R---ESE-R-h-m---M---S---b---SRS-b-o-e---E---R---h---O---M---E---S---R---b-h-ese-hoh-bhb-s-r-b-r-h-b-----b-S-M-B-----B-M-S-b-m-s-B-----"*2,
"e---m---o---a---b---R---S---E-S-R-b-E---_---------e---s---d---r---B---A---O---M---OAO-BAB-OMO-ESE---r---e---m---h---R-,-S---B---s---e---o---b-,-R---r---e---m---o---h---b---e---o---m-R-h-R-e-R-s---e---m---B-bhb-mem-srs-mem-srs-BHB-----,-b-'-"*2,
]
# Q. How does this compare to using zip_events later?
def ev_parts(parts, octaves=None, dur=DURATION,
vel=VELOCITY, show_notes=None):
global SHOW_NOTES
if show_notes is None: show_notes = SHOW_NOTES
if octaves: # transpose as needed
for i,part in enumerate(parts):
parts[i] = up(parts[i], octaves[i]*12)
combined = izip(*parts)
for e in ev_pitches(combined, dur=dur, vel=vel,
show_notes=show_notes):
yield e
def ev_strns(strns, octaves=None, dur=DURATION,
vel=VELOCITY, show_notes=None):
global SHOW_NOTES
if show_notes is None: show_notes = SHOW_NOTES
parts = [strn2pitches(s) for s in strns]
for e in ev_parts(parts, octaves=octaves, dur=dur,
vel=vel, show_notes=show_notes):
yield e
def play_strns(strns, octaves=None, dur=None,
vel=VELOCITY, show_notes=None):
playe(ev_strns(strns, octaves=octaves, dur=dur,
vel=vel, show_notes=show_notes))
def play_whatever(thing, show_notes=None):
global SHOW_NOTES
if show_notes is None: show_notes = SHOW_NOTES
err = ValueError('Unknown thing ' + thing + ' given to play_whatever()')
if isinstance(thing, str):
play_strn(thing, show_notes=show_notes)
elif is_listy(thing) and len(thing) > 0:
if isinstance(thing[0], str):