我正在制作一个能够从某个midi文件中提取音符,休止符和和弦的程序,并将音符和和弦的相应音高(以midi音调数字 - 从0-127开始)写入一个csv文件供以后使用。
对于这个项目,我使用的是Python Library" Music21"。
from music21 import *
import pandas as pd
#SETUP
path = r"Pirates_TheCarib_midi\1225766-Pirates_of_The_Caribbean_Medley.mid"
#create a function for taking parsing and extracting the notes
def extract_notes(path):
stm = converter.parse(path)
treble = stm[0] #access the first part (if there is only one part)
bass = stm[1]
#note extraction
notes_treble = []
notes_bass = []
for thisNote in treble.getElementsByClass("Note"):
indiv_note = [thisNote.name, thisNote.pitch.midi, thisNote.offset]
notes_treble.append(indiv_note) # print's the note and the note's
offset
for thisNote in bass.getElementsByClass("Note"):
indiv_note = [thisNote.name, thisNote.pitch.midi, thisNote.offset]
notes_bass.append(indiv_note) #add the notes to the bass
return notes_treble, notes_bass
#write to csv
def to_csv(notes_array):
df = pd.DataFrame(notes_array, index=None, columns=None)
df.to_csv("attempt1_v1.csv")
#using the functions
notes_array = extract_notes(path)
#to_csv(notes_array)
#DEBUGGING
stm = converter.parse(path)
print(stm.parts)
这是我用作测试的分数的链接。 https://musescore.com/user/1699036/scores/1225766
当我运行extract_notes函数时,它返回两个空数组和行:
print(stm.parts)
它返回
<music21.stream.iterator.StreamIterator for Score:0x1b25dead550 @:0>
我很困惑为什么会这样做。这件作品应该有两个部分,高音和低音。如何将每个音符,和弦和休息放入一个数组中,以便将其放入csv文件中?
答案 0 :(得分:2)
这是我做的小片段。我需要获得特定乐器的所有音符,和弦和休止符。所以起初我通过部分迭代并找到特定的工具,然后检查它是什么类型的笔记并附加它。
您可以像
一样调用此方法notes = get_notes_chords_rests(keyboard_instruments, "Pirates_of_The_Caribbean.mid")
其中keyboard_instruments是乐器列表。
keyboard_nstrument = ["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
P.S。使用try块很重要,因为Web上的很多midi文件都已损坏。