pythonmidimusic21midi-instrument

How to get midi track instrument name with python?


The only way to do it I found is to use music21:

m = converter.parse(path)
for m in m.parts:
    print(m[0])

but it's output is incorrect:

Piano


Piano

empty places is also an instrument names, it just can't read it, but problem is not in file, cause I can import it to the tuxguitar correctly. Also music21 can't pase big midi files and stuck. I tried mido library, but there is no way to get track instrument, I found an attribute, but have no ideas how to use it.

How can I parse instruments of midi tracks with python?


Solution

  • Why didn't Mido work?

    from mido import MidiFile
    mid = MidiFile('song.mid')  
    for i, track in enumerate(mid.tracks):
        print('Track {}: {}'.format(i, track.name))
        for msg in track:
            print(msg)
    

    The tracks attribute is a list of tracks. Each track is a list of messages and meta messages, with the time attribute of each messages set to its delta time (in ticks).
    More info can be found here.