简体   繁体   中英

Is there a way to read Rests from a musicxml file using music21?

I am trying to read a musicxml file with music21 into a list. I'm keeping it very simple. sheetmusic

I've tried the code below but even though it adds the notes without problem, it skips the rest.

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)

My output is currently this:

[[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']]

How can I change it so that I can get the information about the rest too?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM