2012-12-18 42 views
1

我在下面的答案中的代码将字符串中的音符(如C#-4F-3)转换为其对应的MIDI音符值。Python中的音符字符串(C#-4,F-3等)在Python

我发布这个,因为我厌倦了试图每次我需要它在网上挖掘它。我相信我不是唯一能找到它的人。我只是写了这个 - 它测试和正确。它在Python中,但我觉得它非常接近普遍可以理解的。

回答

1
#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