0

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?

user7745819
  • 15
  • 1
  • 4

2 Answers2

5

Instruments are set in MIDI Files in a program change message.

For instance:

mid = mido.MidiFile('PaintItBlack.mid')

for msg in mid:
    if msg.type == 'program_change':
        print(msg)

This will yield

program_change channel=1 program=32 time=0
program_change channel=2 program=27 time=0
program_change channel=3 program=27 time=0
program_change channel=4 program=27 time=0
program_change channel=5 program=25 time=0
program_change channel=6 program=27 time=0
program_change channel=7 program=104 time=0
program_change channel=8 program=30 time=0
program_change channel=10 program=52 time=0

where the channel program value is the instrument for that channel.

For example, program 27 is an Electric Guitar.

Refer to https://jazz-soft.net/demo/GeneralMidi.html to find program instruments.

borne
  • 51
  • 1
  • 2
1

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.

crux666
  • 87
  • 4