Search code examples
pythonaudiomidiaudio-processingmusic21

How to split midi file based on notes pitch using python?


How can I split midi files based on their pitch using python? I tried the music21 library, but I don't really know how this works...


Solution

  • Try this code:

    import pretty_midi
    import copy
    
    pitch_cutoff = 65
    
    mid = pretty_midi.PrettyMIDI('my_file.mid')
    low_notes = copy.deepcopy(mid)
    high_notes = copy.deepcopy(mid)
    
    for instrument in low_notes.instruments:
        for note in instrument.notes:
            if note.pitch > pitch_cutoff:
                note.velocity = 0
    
    for instrument in high_notes.instruments:
        for note in instrument.notes:
            if note.pitch < pitch_cutoff:
                note.velocity = 0
    
    low_notes.write("low_notes.mid")
    high_notes.write("high_notes.mid")
    

    it uses the pretty_midi module to split a midi file into two different files. The file called "high_notes.mid" will only have notes above what you set the pitch_cutoff variable to, and "low_notes.mid" will only have notes below that. Just change "my_file.mid" to whatever the name of your file is and try it out. Let me know if you have any questions.