'split midi file for each bar in python

I want to divide the MIDI file in python into bars and get the notes in that bars. So I use music21 library and I can get the notes but I can't split it up by bar. I want to know what kind of notes are in bar 1 and what are in bar 2. I hope I can get some help with this problem.Thank you.



Solution 1:[1]

In recent versions of music21 (v7+ released after this question was first posted), you can just load the MIDI file and iterate on each measure, using the .measure(num) function and checking if the item returned has any measures in it:

myScore = converter.parse('filename.mid')
i = 1
while (measureStack := myScore.measure(i))[stream.Measure]:
    print(len(measureStack[note.Note]))
    i += 1

Prior to v7, you'll want to run myScore.makeMeasures(inPlace=True) before running this code. (Before v7, you'll also want to call .recurse().getElementsByClass(XXXX) instead of [XXXX]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Scott Asato Cuthbert