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

323 views Asked by At

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?

1

There are 1 answers

0
Zeynep Yılmaz On

Here's what solved my issue.

I had to check if a note is a rest or not using .isRest method. You can fund the solution below.

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