You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
1.2 KiB
40 lines
1.2 KiB
import mido
|
|
|
|
|
|
def process(midi: mido.MidiFile, tracks: set[int] | None = None) -> mido.MidiFile:
|
|
cleaned_midi = mido.MidiFile()
|
|
cleaned_midi.ticks_per_beat = midi.ticks_per_beat
|
|
|
|
for i, track in enumerate(midi.tracks):
|
|
if tracks is not None and i not in tracks:
|
|
cleaned_midi.tracks.append(track)
|
|
continue
|
|
|
|
cleaned_track = mido.MidiTrack()
|
|
last_state = {}
|
|
last_msg = None
|
|
|
|
for msg in track:
|
|
|
|
if last_msg is not None and msg == last_msg:
|
|
continue
|
|
|
|
if msg.type in ['control_change', 'program_change', 'pitchwheel', 'aftertouch', 'channel_pressure']:
|
|
channel = msg.channel
|
|
key = f"{msg.type}_{channel}"
|
|
if key in last_state and last_state[key] == msg:
|
|
continue
|
|
last_state[key] = msg
|
|
cleaned_track.append(msg)
|
|
elif msg.type == 'note_off':
|
|
cleaned_track.append(msg)
|
|
elif msg.type == 'note_on' and msg.velocity == 0:
|
|
cleaned_track.append(msg)
|
|
else:
|
|
cleaned_track.append(msg)
|
|
|
|
last_msg = msg
|
|
|
|
cleaned_midi.tracks.append(cleaned_track)
|
|
|
|
return cleaned_midi
|