music21: get the voice/program/instrument of midi voice from a flat score?

469 Views Asked by At

I have a simple script that uses music21 to process the notes in a midi file:

import music21

score = music21.converter.parse('www.vgmusic.com/music/console/nintendo/nes/zanac1a.mid')

for i in score.flat.notes:
  
  print(i.offset, i.quarterLength, i.pitch.midi)

Is there a way to also obtain a note's voicing / midi program using a flat score? Any pointers would be appreciated!

1

There are 1 best solutions below

1
Jacob Walls On BEST ANSWER

MIDI channels and programs are stored on Instrument instances, so use getContextByClass(instrument.Instrument) to find the closest Instrument in the stream, and then access its .midiProgram.

Be careful:

  • .midiChannel and .midiProgram are 0-indexed, so MIDI channel 10 will be 9 in music21, etc., (we're discussing changing this behavior in the next release)
  • Some information might be missing if you're not running the bleeding edge version (we merged a patch yesterday on this topic), so I advise pulling from git: pip install git+https://github.com/cuthbertLab/music21
  • .flat is going to kill you, though, if the file is multitrack. If you follow my advice you'll just get the last instrument on every track. 90% of the time people doing .flat actually want .recurse().