首页 > 解决方案 > 有没有办法使用 music21 从 musicxml 文件中读取 Rests?

问题描述

我正在尝试将带有 music21 的 musicxml 文件读入列表。我保持非常简单。 乐谱

我已经尝试了下面的代码,但即使它毫无问题地添加了注释,它也会跳过其余部分。

def xml_to_list():
    fn = "Untitled.xml"
    xml_data = m12.converter.parse(fn)
    score = []
    for part in xml_data.parts:
        instrument = part.getInstrument().instrumentName
        for note in part.recurse().notes:
            start = note.offset
            duration = note.quarterLength
            pitch = note.pitch.ps
            score.append([start, duration, pitch, instrument])
    print(score)

我的输出目前是这样的:

[[0.0, 1.0, 72.0, 'Piano'], [1.0, 1.0, 74.0, 'Piano'], [2.0, 1.0, 76.0, 'Piano'], [0.0, 1.0, 79.0, 'Piano'], [1.0, 1.0, 79.0, 'Piano'], [2.0, 1.0, 79.0, 'Piano'], [3.0, 1.0, 77.0, 'Piano']]

如何更改它以便我也可以获得有关其余部分的信息?

标签: pythonmusic21musicxml

解决方案


def xml_to_list(xml):
    xml_data = m21.converter.parse(xml)
    score = []
    for part in xml_data.parts:
        for note in part.recurse().notesAndRests:
            if note.isRest:
                start = note.offset
                duration = note.quarterLength
                score.append([start, duration, -1])
            else:
                start = note.offset
                duration = note.quarterLength
                pitch = note.nameWithOctave
                score.append([start, duration, pitch])
    return score

推荐阅读