Last active
December 31, 2022 23:22
-
-
Save 0187773933/50c23096908acd3ddffe17a3dae3b039 to your computer and use it in GitHub Desktop.
Transpose MIDI To All Key Variations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
from music21 import * | |
from pathlib import Path | |
keys = [ "A" , "B" , "C" , "D" , "E" , "F" , "G" ] | |
key_modifiers = [ '####' , '###' , '##' , '#~' , '#' , '~' , '----' , '---' , '--' , '-`' , '-' , '`' , '' ] | |
key_modifier_names = [ 'quadruple-sharp' , 'triple-sharp' , 'double-sharp' , 'one-and-a-half-sharp' , 'sharp' , 'half-sharp' , 'quadruple-flat' , 'double-flat' , 'one-and-a-half-flat' , 'flat' , 'half-flat' , 'natural' ] | |
if __name__ == "__main__": | |
input_midi = Path( sys.argv[ 1 ] ) | |
output_folder = input_midi.parent.joinpath( f"{input_midi.stem} - Keys" ) | |
output_folder.mkdir( exist_ok=True , parents=True ) | |
midi = converter.parse( str( input_midi ) ) | |
original_key = midi.analyze( "key" ) | |
original_key_tonic = original_key.tonic | |
for key_index , key in enumerate( keys ): | |
for key_modifier_index , key_modifier in enumerate( key_modifiers ): | |
transposed_key = f"{key}{key_modifier}" | |
if transposed_key == original_key_tonic: | |
continue | |
try: | |
transposed_pitch = pitch.Pitch( transposed_key ) | |
transposition = interval.Interval( original_key_tonic , transposed_pitch ) | |
output_midi_file_path = output_folder.joinpath( f"{input_midi.stem} - {transposed_key}.mid" ) | |
output_pdf_file_path = output_folder.joinpath( f"{input_midi.stem} - {transposed_key}.pdf" ) | |
transposed_midi_file = midi.transpose( transposition ) | |
transposed_midi_file.write( "midi" , fp=output_midi_file_path ) | |
# transposed_midi_file.write( "pdf" , fp=output_pdf_file_path ) | |
print( f"Transposed from {original_key_tonic} to {transposed_key} === {key_modifier_names[key_modifier_index]}" ) | |
except Exception as e: | |
print( key_index , key_modifier_index , e ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment