-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_music.py
85 lines (71 loc) · 2.78 KB
/
create_music.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
import os
import sys
from fractions import gcd
from functools import reduce
import midi
def filter_track(track):
newtrack = midi.Track([], False)
last_tick = 0
for n, e in enumerate(track):
if isinstance(e, midi.NoteOnEvent) and ((midi.C_4 > e.pitch < midi.C_7) or e.velocity == 0):
continue
if isinstance(e, midi.NoteOnEvent) \
and len(newtrack) > 0 \
and isinstance(newtrack[-1], midi.NoteOnEvent) \
and e.tick - last_tick == 0:
if e.pitch > newtrack[-1].pitch:
newtrack[-1].pitch = e.pitch
else:
newtrack.append(e)
last_tick = e.tick
return newtrack
def note_frequency(note):
return 440 * (2.0 ** ((note - midi.A_4) / 12.0))
TIMER_DIVISOR = 64
def main():
cpufreq = int(sys.argv[1])
pattern = midi.read_midifile(os.path.join(os.path.dirname(__file__), "Korobeiniki.mid"))
pattern.make_ticks_abs()
track = filter_track(pattern[0])
pattern[0] = midi.Track(track, False)
pattern.make_ticks_rel()
midi.write_midifile(os.path.join(os.path.dirname(__file__), "Korobeiniki-filtered.mid"), pattern)
used_notes = {e.pitch for e in track if isinstance(e, midi.NoteOnEvent)}
note_map = {note: n for n, note in enumerate(used_notes)}
print("#ifndef TUNE_H")
print("#define TUNE_H")
print("#include <stdint.h>")
print("#include <avr/pgmspace.h>")
print
print("/* Autogenerated by %s - do not edit */" % os.path.basename(__file__))
print
print("typedef struct {")
print(" uint8_t note: 5, time: 3;")
print("} _note;")
print
print("typedef union {")
print(" _note;")
print(" uint8_t decode;")
print("} note;")
print
print("const uint8_t note_clocks[] = {")
print("\n".join(" %d, // %s" % (round((cpufreq / TIMER_DIVISOR / 2) / note_frequency(note)),
midi.NOTE_VALUE_MAP_SHARP[note].replace("_", "").replace("s", "#"))
for note in note_map))
print("};")
print
print("const _note tune[] PROGMEM = {")
track_notes = [event for event in track if isinstance(event, midi.NoteOnEvent)]
note_ticks = {event.tick for event in track_notes}
note_gcd = reduce(gcd, note_ticks)
print("\n".join(" {%d, %d}, // %s" % (note_map[event.pitch],
(nextevent.tick / note_gcd) - 1,
midi.NOTE_VALUE_MAP_SHARP[event.pitch])
for event, nextevent in zip(track_notes, track_notes[1:])))
print("};")
print("#define TUNE_LENGTH %d" % (len(track_notes) - 1))
print("#define NOTE_LENGTH_MULTIPLIER %d" % note_gcd)
print
print("#endif // TUNE_H")
if __name__ == "__main__":
sys.exit(main())