使用带有partitionByInstrument()的music21读取MIDI文件以获取返回空列表的音符和和弦

时间:2020-10-18 13:37:12

标签: midi music21

我正在尝试使用此github repository's .py file中的代码(get_notes()函数)从this midi file中提取音符和和弦数据。这是从我正在使用的仓库中复制的确切代码:

def get_notes():
    """ Get all the notes and chords from the midi files in the ./midi_songs directory """
    notes = []

    for file in glob.glob("midi_songs/*.mid"):
        midi = converter.parse(file)

        print("Parsing %s" % file)

        notes_to_parse = None

        try: # file has instrument parts
            s2 = instrument.partitionByInstrument(midi)
            notes_to_parse = s2.parts[0].recurse() 
        except: # file has notes in a flat structure
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                notes.append('.'.join(str(n) for n in element.normalOrder))

    with open('data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)

    return notes

我的midi文件具有多种乐器,我认为由于某种原因,该乐器没有任何内容附加到音符列表中。看到我刚刚克隆了存储库的代码并在我自己的midi文件上运行它,我不确定为什么它不起作用。我浏览了music21的partitionByInstrument()的文档,并尝试通过更改以下内容来迭代不同的乐器:

notes_to_parse = s2.parts[0].recurse()

 notes_to_parse = s2.parts[1].recurse()

因为不同的部分应该是文件中的不同乐器,但是它仍然返回一个空列表。我该怎么办?

2 个答案:

答案 0 :(得分:2)

v6.1 添加了一项功能,可根据 MIDI 乐器名称和轨道名称消息创建 Instrument 对象。今天发布的 v6.5 添加了一项功能,可以删除在同一滴答声中程序更改消息中还有 Instrument 时导致的重复项。如果您试用 v6.5,您可能会发现它更易于使用。

答案 1 :(得分:0)

这只是事实,它正在使用发现的第一把乐器,没有关于音符,时长或偏移的数据。遍历这些工具,我得到了不同的工具,它们返回了完整列表。