-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconvert.py
56 lines (38 loc) · 1.57 KB
/
convert.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
import music21
import sys
from note_util import GANote
# Will create melody
# You still need to write underlying chord progression manually
def convert(filename):
score = music21.converter.parse(filename, format='musicxml')
notes = [n for n in score.recurse().notesAndRests]
formatted_piece = []
current_measure_length = 0
max_measure_length = 4
current_measure = []
for note in notes:
duration = note.quarterLength
# don't bother with v small things
if duration < 1e-10:
continue
if duration >= max_measure_length * 2:
print("Please don't use long notes; keep it to a whole note at the largest, and avoid slurs as we'll break those")
print("Cancelling")
sys.exit(0)
pitch = None
if hasattr(note, 'pitch'):
pitch = note.pitch.midi
if current_measure_length + duration > max_measure_length:
first_half = GANote(pitch, max_measure_length - current_measure_length)
second_half = GANote(pitch, duration - (max_measure_length - current_measure_length))
if first_half.duration > 1e-10:
current_measure.append(first_half)
formatted_piece.append(current_measure)
current_measure = [second_half]
current_measure_length = second_half.duration
else:
current_measure.append(GANote(pitch, duration))
current_measure_length += duration
if len(current_measure) != 0:
formatted_piece.append(current_measure)
return formatted_piece