Repository navigation
Expand file tree
/
Copy pathmidi_generator.py
More file actions
52 lines (39 loc) · 1.61 KB
/
Copy pathmidi_generator.py
File metadata and controls
52 lines (39 loc) · 1.61 KB
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
"""MIDI generation module.
Creates a MIDI file from a prediction array output by interpreting and converting the data back into musical
representation by 'music21'.
"""
# Import libraries.
from music21 import instrument, note, chord, stream
import time
def create_midi(prediction_output, network_type):
""" convert the output from the prediction to notes and create a midi file
from the notes """
print('Generating MIDI file...')
offset = 0
output_notes = []
# Create note and chord objects based on the values generated by the model.
for element in prediction_output:
if ('.' in element) or element.isdigit():
# Element is a chord.
notes_in_chord = element.split('.')
notes = []
for current_note in notes_in_chord:
new_note = note.Note(int(current_note))
new_note.storedInstrument = instrument.Piano()
notes.append(new_note)
new_chord = chord.Chord(notes)
new_chord.offset = offset
output_notes.append(new_chord)
else:
# Element is a note.
new_note = note.Note(element)
new_note.offset = offset
new_note.storedInstrument = instrument.Piano()
output_notes.append(new_note)
# Increase offset each iteration to prevent notes stacking.
offset += 1
midi_stream = stream.Stream(output_notes)
file_name = 'output_' + network_type + '_' + time.strftime("%Y%m%d-%H%M%S") + '.mid'
midi_stream.write('midi', fp=file_name)
print('MIDI file generated.')
midi_stream.show()