-
Notifications
You must be signed in to change notification settings - Fork 51
/
22.ex-midi-markov-learner.py
executable file
·66 lines (52 loc) · 1.87 KB
/
22.ex-midi-markov-learner.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
#!/usr/bin/env python3
#------------------------------------------------------------------------
# Parallel markov chain learner:
#
# 1. takes MIDI input, and constructs three markov chains for pitch,
# duration and amplitude.
# 2. after receiving a keyboard interrupt (ctrl-c), plays back melodies
# that are statistically similar to the input.
#------------------------------------------------------------------------
from isobar import *
import logging
import time
def main():
midi_in = MidiInputDevice()
midi_out = MidiOutputDevice()
learner = MarkovParallelLearners(3)
clock0 = time.time()
print("Listening for MIDI events...")
try:
while True:
message = midi_in.poll()
if message is not None and message.type == "note_on":
clock = time.time()
print("[%f] %s (%d, %d)" % (clock, message, message.note, message.velocity))
velocity = round(message.velocity, -1)
dur = clock - clock0
dur = round(dur, 2)
learner.register([message.note, velocity, dur])
clock0 = clock
except KeyboardInterrupt:
pass
print("----------------------------------------------------")
print("Ctrl-C detected, now playing back")
print("----------------------------------------------------")
chains = learner.chains()
pitch = chains[0]
amp = chains[1]
dur = chains[2]
if len(pitch.nodes) == 0:
print("No notes detected")
else:
timeline = Timeline(120, midi_out)
timeline.schedule({
"note": pitch,
"duration": dur,
"amplitude": amp,
"channel": 0
})
timeline.run()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(message)s")
main()