-
Notifications
You must be signed in to change notification settings - Fork 0
/
midi_preproc.py
58 lines (42 loc) · 1.79 KB
/
midi_preproc.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
from music21 import converter, stream, note, chord, duration, pitch
from scipy.sparse import csc_matrix
import os.path
import pickle as pkl
import numpy as np
instruments = ['Piano', 'Guitar', 'Violin']
def midiToMatrix(filename):
if os.path.isfile(filename+'.prep') :
f = open(filename+'.prep', 'rb')
return pkl.load(f)
parsed = converter.parse(filename)
party = []
for part in parsed:
for voice in part.getElementsByClass(stream.Voice):
if voice.getInstrument().instrumentName in instruments:
for thisNote in [n for n in voice if (isinstance(n,note.Note) or isinstance(n,chord.Chord))]:
cur_chord = np.zeros(129)
for _pitch in thisNote.pitches:
cur_chord[_pitch.midi] = 1
#text += pitch.name+str(pitch.octave)
dur = thisNote.duration.quarterLength
cur_chord[-1] = dur#dur.numerator / float(dur.denominator)
party.append(cur_chord)
#text += dur_to_text(thisNote.duration.type)+'z'
res= csc_matrix(party) if len(party) > 0 else csc_matrix(np.zeros((0,129)))
with open(filename+'.prep', 'wb') as f:
pkl.dump(res,f)
return res;
from music21 import midi
def save_mat2_mid(mat, fname='output/test.mid'):
music_stream = stream.Stream()
for dense_line in np.array(mat):
(notes,) = np.where(dense_line[:-1]>0.5)
pitches = []
for n in notes:
pitches.append(pitch.Pitch(midi=n))
crd = chord.Chord(notes= pitches, quarterLength=np.round(dense_line[-1]*2048)/2048)
music_stream.append(crd)
md = midi.translate.streamToMidiFile(music_stream)
md.open(fname, 'wb')
md.write()
md.close()