-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmidi.py
More file actions
144 lines (118 loc) · 6.52 KB
/
midi.py
File metadata and controls
144 lines (118 loc) · 6.52 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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
##################################################################################
# MIDI processing #
##################################################################################
# #
# Johannes Zeitler ([email protected]), 2026 #
# #
# If you use this code, please cite our paper: #
# Johannes Zeitler and Meinard Müller. Subsequence SDTW: Differentiable #
# Alignment with Flexible Boundary Conditions. IEEE International Conference on #
# Acoustics, Speech, and Signal Processing (ICASSP), Barcelona, Spain, 2026. #
##################################################################################
##################################################################################
# MIT License #
# #
# Copyright 2026 Johannes Zeitler #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in all #
# copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #
# SOFTWARE. #
##################################################################################
import multiprocessing
import sys
import mido
import numpy as np
from joblib import Parallel, delayed
from mido import Message, MidiFile, MidiTrack
from mir_eval.util import hz_to_midi
from tqdm import tqdm
def parse_midi(path):
"""open midi file and return np.array of (onset, offset, note, velocity) rows"""
midi = mido.MidiFile(path)
time = 0
sustain = False
events = []
for message in midi:
time += message.time
if message.type == 'control_change' and message.control == 64 and (message.value >= 64) != sustain:
# sustain pedal state has just changed
sustain = message.value >= 64
event_type = 'sustain_on' if sustain else 'sustain_off'
event = dict(index=len(events), time=time, type=event_type, note=None, velocity=0)
events.append(event)
if 'note' in message.type:
# MIDI offsets can be either 'note_off' events or 'note_on' with zero velocity
velocity = message.velocity if message.type == 'note_on' else 0
event = dict(index=len(events), time=time, type='note', note=message.note, velocity=velocity, sustain=sustain)
events.append(event)
notes = []
for i, onset in enumerate(events):
if onset['velocity'] == 0:
continue
# find the next note_off message
offset = next(n for n in events[i + 1:] if n['note'] == onset['note'] or n is events[-1])
if offset['sustain'] and offset is not events[-1]:
# if the sustain pedal is active at offset, find when the sustain ends
offset = next(n for n in events[offset['index'] + 1:]
if n['type'] == 'sustain_off' or n['note'] == onset['note'] or n is events[-1])
note = (onset['time'], offset['time'], onset['note'], onset['velocity'])
notes.append(note)
return np.array(notes)
def save_midi(path, pitches, intervals, velocities):
"""
Save extracted notes as a MIDI file
Parameters
----------
path: the path to save the MIDI file
pitches: np.ndarray of bin_indices
intervals: list of (onset_index, offset_index)
velocities: list of velocity values
"""
file = MidiFile()
track = MidiTrack()
file.tracks.append(track)
ticks_per_second = file.ticks_per_beat * 2.0
events = []
for i in range(len(pitches)):
events.append(dict(type='on', pitch=pitches[i], time=intervals[i][0], velocity=velocities[i]))
events.append(dict(type='off', pitch=pitches[i], time=intervals[i][1], velocity=velocities[i]))
events.sort(key=lambda row: row['time'])
last_tick = 0
for event in events:
current_tick = int(event['time'] * ticks_per_second)
velocity = int(event['velocity'] * 127)
if velocity > 127:
velocity = 127
pitch = int(round(hz_to_midi(event['pitch'])))
track.append(Message('note_' + event['type'], note=pitch, velocity=velocity, time=current_tick - last_tick))
last_tick = current_tick
file.save(path)
if __name__ == '__main__':
def process(input_file, output_file):
midi_data = parse_midi(input_file)
np.savetxt(output_file, midi_data, '%.6f', '\t', header='onset\toffset\tnote\tvelocity')
def files():
for input_file in tqdm(sys.argv[1:]):
if input_file.endswith('.mid'):
output_file = input_file[:-4] + '.tsv'
elif input_file.endswith('.midi'):
output_file = input_file[:-5] + '.tsv'
else:
print('ignoring non-MIDI file %s' % input_file, file=sys.stderr)
continue
yield (input_file, output_file)
Parallel(n_jobs=multiprocessing.cpu_count())(delayed(process)(in_file, out_file) for in_file, out_file in files())