以下程序将 midi 文件解析出来, 并利用解析出来的音符重新生成一个一样的 midi 文件。
import mido import sys import json def midifile_to_dict(mid): tracks = [] for track in mid.tracks: tracks.append([vars(msg).copy() for msg in track]) return { 'ticks_per_beat': mid.ticks_per_beat, 'tracks': tracks, } mid = mido.MidiFile("Pianoboy-你离开的事实_爱给网_aigei_com.mid", clip=True) dict_mid = midifile_to_dict(mid) json_mid = json.dumps(dict_mid, indent=2) print(json_mid) track0 = (dict_mid["tracks"])[0] track1 = (dict_mid["tracks"])[1] track2 = (dict_mid["tracks"])[2] ######### EXTRACT MUSIC DATA FROM THE TWO MAIN TRACKS ########## on_off1=[] note1_on=[] note1_off=[] velocity1_on=[] velocity1_off=[] time1_on=[] time1_off=[] on_off2=[] note2_on=[] note2_off=[] velocity2_on=[] velocity2_off=[] time2_on=[] time2_off=[] for i, msg in enumerate(track1): if msg["type"] is "note_on": on_off1.append(1) note1_on.append(msg["note"]) velocity1_on.append(msg["velocity"]) time1_on.append(msg["time"]) if msg["type"] is "note_off": on_off1.append(0) note1_off.append(msg["note"]) velocity1_off.append(msg["velocity"]) time1_off.append(msg["time"]) for i, msg in enumerate(track2): if msg["type"] is "note_on": on_off2.append(1) note2_on.append(msg["note"]) velocity2_on.append(msg["velocity"]) time2_on.append(msg["time"]) if msg["type"] is "note_off": on_off2.append(0) note2_off.append(msg["note"]) velocity2_off.append(msg["velocity"]) time2_off.append(msg["time"]) ######### CREATE NEW MIDI FILE ############ outfile = mido.MidiFile() outtrack0 = mid.tracks[0] outtrack1 = mido.MidiTrack() outtrack2 = mido.MidiTrack() outfile.tracks.append(outtrack0) outfile.tracks.append(outtrack1) outfile.tracks.append(outtrack2) for i in range(len(on_off1)): if on_off1[i]: outtrack1.append(mido.Message('note_on', note=note1_on.pop(0), velocity=velocity1_on.pop(0), time=time1_on.pop(0))) else: outtrack1.append(mido.Message('note_off', note=note1_off.pop(0), velocity=velocity1_off.pop(0), time=time1_off.pop(0))) for i in range(len(on_off2)): if on_off2[i]: outtrack2.append(mido.Message('note_on', note=note2_on.pop(0), velocity=velocity2_on.pop(0), time=time2_on.pop(0))) else: outtrack2.append(mido.Message('note_off', note=note2_off.pop(0), velocity=velocity2_off.pop(0), time=time2_off.pop(0))) outfile.save('createtest.mid')