Search code examples
pythonmusic21

How to retrieve the left and right hand of a piano piece using Music21


I'm trying to retrieve the right hand and left hand notes of a piano piece with two staves for music analysis but I'm having a lot of trouble achieving this.

I'm using Music21 to do this. In their documentation, it seems like a Part class corresponds to a staff so I thought getting the Part objects of a stream object would retrieve the left hand(Part object) and the right hand(Part object).

curr_stream = converter.parse(str(file))
parts = curr_stream.getElementsByClass(stream.Part)
left_hand = parts[0]
right_hand = parts[1]

Since the song has two staves, I expect there to be two parts but for some songs that have two staves this isn't the case. Some songs that clearly have two staves only have one part in the stream object.


Solution

  • Everything depends on what str(file) is. For MusicXML files that are properly encoded with one musicxml part and multiple staves encoded, music21 will create two PartStaff objects. PartStaff is a subclass of stream.Part, so your code would work (as would curr_stream.parts). See for instance, corpus.parse('cpebach'). But there are lots of miscoded piano pieces out there.