这是我如何做到这一点的一小段。我需要获取特定乐器的所有音符、和弦和休止符。因此,首先我迭代了部分并找到了特定的乐器,然后检查它是什么类型的注释并将其附加。
你可以这样调用这个方法:
notes = get_notes_chords_rests(keyboard_instruments, "Pirates_of_The_Caribbean.mid")
其中 Keyboard_instruments 是乐器列表:
keyboard_instruments = ["KeyboardInstrument", "Piano", "Harpsichord", "Clavichord", "Celesta", ]
def get_notes_chords_rests(instrument_type, path):
try:
midi = converter.parse(path)
parts = instrument.partitionByInstrument(midi)
note_list = []
for music_instrument in range(len(parts)):
if parts.parts[music_instrument].id in instrument_type:
for element_by_offset in stream.iterator.OffsetIterator(parts[music_instrument]):
for entry in element_by_offset:
if isinstance(entry, note.Note):
note_list.append(str(entry.pitch))
elif isinstance(entry, chord.Chord):
note_list.append('.'.join(str(n) for n in entry.normalOrder))
elif isinstance(entry, note.Rest):
note_list.append('Rest')
return note_list
except Exception as e:
print("failed on ", path)
pass
附:使用 try 块很重要,因为网络上的许多 midi 文件都已损坏。