Search code examples
stringformatintmidi

Musical note string (C#-4, F-3, etc.) to MIDI note value, in Python


The code in my answer below converts musical notes in strings, such as C#-4 or F-3, to their corresponding MIDI note values.

I am posting this because I am tired of trying to dig it up online every time I need it. I'm sure I'm not the only one who can find a use for it. I just wrote this up — it is tested and correct. It's in Python, but I feel that it pretty close to universally understandable.


Solution

  • #Input is string in the form C#-4, Db-4, or F-3. If your implementation doesn't use the hyphen, 
    #just replace the line :
    #    letter = midstr.split('-')[0].upper()
    #with:
    #    letter = midstr[:-1]
    def MidiStringToInt(midstr):
        Notes = [["C"],["C#","Db"],["D"],["D#","Eb"],["E"],["F"],["F#","Gb"],["G"],["G#","Ab"],["A"],["A#","Bb"],["B"]]
        answer = 0
        i = 0
        #Note
        letter = midstr.split('-')[0].upper()
        for note in Notes:
            for form in note:
                if letter.upper() == form:
                    answer = i
                    break;
            i += 1
        #Octave
        answer += (int(midstr[-1]))*12
        return answer