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?
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.