converting a midi file into snap xml file

The very first message in your MIDI file is a program_change message, which does not have a note attribute:

program_change channel=0 program=0 time=0

The messages following it, however, have a note attribute:

note_on channel=0 note=60 velocity=63 time=0
note_on channel=0 note=82 velocity=12 time=0.09302325581395349
note_on channel=0 note=98 velocity=13 time=0.03488372093023256
note_off channel=0 note=98 velocity=64 time=0.03488372093023256
note_on channel=0 note=48 velocity=24 time=0.03488372093023256
note_on channel=0 note=96 velocity=12 time=0
...

So, it’s your very first message that’s raising an exception. One solution would be to just consume the first message from the message iterator, and then iterate through all the ones after it:

def main():
    import mido
    from mido import MidiFile

    messages = MidiFile("HSSWake.mid").play()
    _ = next(message)

    for message in messages:
        # do stuff with message

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

However, I didn’t sit through and look at EVERY single message in your MIDI, so it could be that there are other messages that occur later on which also don’t have a note attribute. In that case, you could skip any messages which don’t have a note attribute in the loop:

def main():
    import mido
    from mido import MidiFile

    for message in MidiFile("HSSWake.mid").play():
        try:
            print(message.note)
        except AttributeError:
            print("Skipping message without 'note' attribute...")
            continue

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

Alternatively, instead of a try-except block, you could just look at each message’s type to figure out if it has a note attribute. Basically, just skip all messages that are not note_on messages:

for message in MidiFile("HSSWake.mid").play():
        if message.type != "note_on":
            continue
        print(message.note)

This means you will only print the note attribute of note_on messages. All other message types (even ones like note_off which have a note attribute) are excluded.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top