4

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.

sudal
  • 41
  • 1
  • Please post your code showing your best attempt to reach a target. Each bar (measure) will have several channels (of voices, instruments). Focus only what you need. – swatchai Jul 25 '18 at 07:17
  • With [DryWetMidi](https://github.com/melanchall/drywetmidi) (.NET library) you can split a MIDI file by grid with step of 1 bar and get notes for each new file: `var newFiles = midiFile.SplitByGrid(new SteppedGrid(new BarBeatTimeSpan(1, 0, 0))); var firstBarNotes = newFiles.First().GetNotes();`. Maybe in music21 there is something similar? – Maxim Aug 16 '18 at 13:18

1 Answers1

0

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]