-
Notifications
You must be signed in to change notification settings - Fork 53
/
32.ex-midifile-markov.py
executable file
·57 lines (48 loc) · 2.23 KB
/
32.ex-midifile-markov.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
#!/usr/bin/env python3
#------------------------------------------------------------------------
# ex-midifile-markov:
#
# Apply first-order Markov chains to an input MIDI file.
#------------------------------------------------------------------------
from isobar import *
import argparse
import logging
def main():
parser = argparse.ArgumentParser(description="Read and play a .mid file")
parser.add_argument("filename", type=str, help="File to load (.mid)")
args = parser.parse_args()
#------------------------------------------------------------------------
# Quantize durations to the nearest 1/8th note.
#------------------------------------------------------------------------
pattern = MidiFileInputDevice(args.filename).read(quantize=1 / 8)
pattern = PDict(pattern)
#------------------------------------------------------------------------
# Learn note, duration and amplitude series separately.
#------------------------------------------------------------------------
note_learner = MarkovLearner()
note_learner.learn_pattern(pattern["note"])
dur_learner = MarkovLearner()
dur_learner.learn_pattern(pattern["duration"])
#------------------------------------------------------------------------
# Quantize velocities to the nearest 10 to make chains easier to
# learn with a small sample set.
#------------------------------------------------------------------------
amp_learner = MarkovLearner()
amp_learner.learn_pattern(PInt(PRound(PScalar(pattern["amplitude"]), -1)))
#------------------------------------------------------------------------
# The markov property of a learner is a PMarkov, which generates
# outputs by traversing the Markov chain stochastically.
#------------------------------------------------------------------------
timeline = Timeline(90)
timeline.schedule({
"note": note_learner.markov,
"duration": dur_learner.markov,
"amplitude": amp_learner.markov
})
try:
timeline.run()
except KeyboardInterrupt:
timeline.output_device.all_notes_off()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(message)s")
main()