如何从midi文件中提取单个和弦、休止符和音符?

2024-10-01 11:29:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个程序,应该能够从某个midi文件中提取音符、休止符和和弦,并将音符和和弦的相应音高(以midi音调编号表示,从0到127)写入csv文件,以备以后使用。

对于这个项目,我使用Python库“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函数时,它返回两个空数组和一行:

^{pr2}$

它回来了

<music21.stream.iterator.StreamIterator for Score:0x1b25dead550 @:0>

我不明白它为什么这样做。这首曲子应该有两部分,高音和低音。如何将每个音符、和弦和休止符放入一个数组中,以便将其放入csv文件中?


Tags: 文件csvthetopathforarraymidi
1条回答
网友
1楼 · 发布于 2024-10-01 11:29:23

下面是我是怎么做到的。我需要得到特定乐器的所有音符、和弦和休息。所以,首先我遍历了部分,找到了特定的工具,然后检查它是什么类型的note并将其追加。在

你可以把这个方法叫做

notes = get_notes_chords_rests(keyboard_instruments, "Pirates_of_The_Caribbean.mid")

其中keyboard_instruments是乐器列表。在

keyboard_nstrument = ["KeyboardInstrument", "Piano", "Harpsichord", "Clavichord", "Celesta", ]

^{pr2}$

另外,使用try block很重要,因为web上的很多midi文件都被破坏了。在

相关问题 更多 >