music21 python trying to get number of notes in treble clef and bass clef separately

137 Views Asked by At

I have the midi file I am using here: https://drive.google.com/file/d/1CKByT17yRVZKRC6fwrVwRJETFGgHg0a6/view?usp=sharing

I would like to have music21 count the number of notes in the treble clef and the bass clef separately for measure 1.

Is there a way to get the counts separately for each clef rather than together?

The first measure looks like this:

First measure

I count 23 notes on the treble and bass clef.

I run this code:

from music21 import converter, note, stream


myScore =converter.parse('/Users/carlkonopka/Downloads/midi/music21.mid')
i = 1
while (measureStack := myScore.measure(i))[stream.Measure]:
    print(len(measureStack[note.Note]))
    i += 1

It says there are 19 notes in the first measure.

I ran the following code to see the notes:

from music21 import converter, note, stream
myScore =converter.parse('/Users/carlkonopka/Downloads/midi/music21.mid')
m=myScore.measures(1,1)
for el in m[note.Note].recurse():
   print(el.show())

When I compare the output to the measure, some of the notes are not there.

1

There are 1 best solutions below

0
Jacob Walls On

Is there a way to get the counts separately for each clef rather than together?

Yes, you should isolate the part you are interested in. This score has two parts, LH and RH, and this is how you can get the count of 11 + 10 notes or chords (I count 21, not 23):

>>> rh = myScore.parts[0]
>>> len(rh[stream.Measure][0].recurse().notes)
11
>>> lh = myScore.parts[1]
>>> len(lh[stream.Measure][0].recurse().notes)
10

Notice I used the .notes filter, which includes both note.Note and chord.Chord. This is why you got fewer than 21 (there were two chords in your excerpt).

If you want to still want to use the bracket syntax, you can filter on the superclass that everything but rests inherit from: note.NotRest:

>>> len(rh[stream.Measure][0][note.NotRest])
11
>>> len(lh[stream.Measure][0][note.NotRest])
10