Search code examples
pythonmidi

Need Loop Function to Analyze the key of MIDI files


I’m working on code for a research project where I need to analyze the key of each file in a folder full of MIDI files and then output the name of each file in an excel sheet in one column and the key of the file in the column next to it.

So far, I only have the below code in the screenshot as I am new to coding in general.

import music21
score = music21.converter.parse('AnyConv.com__P_3_Nov10_MISMATCH_Reciever_Int1-2.midi')
key = score.analyze('key')
print(key.tonic.name, key.mode)

score = music21.converter.parse('AnyConv.com__P_4_Nov10_MISMATCH_Giver_Int1-2.midi')
key = score.analyze('key')
print(key.tonic.name, key.mode)

Solution

  • First you need to list out all the files in the dir with .midi extension.

    import os
    import music21 as m
    
    # traverse whole directory
    for root, dirs, files in os.walk(r'd:/somedir/'):
        # select the file name
        for file in files:
            # check if it is MIDI
            if file.endswith('.midi'):
                # get full path of the file
                midi_file = os.path.join(root, file)
                #score = m.converter.parse(midi_file)
                key = m.converter.parse(midi_file).analyze('key')
                print(file, key.tonic.name, key.mode)