Is there an algorithm to get the Scale and Key of a song from a series of notes?

Amr Hesham picture Amr Hesham · Feb 6, 2013 · Viewed 7.4k times · Source

I've got a series of MIDI notes stored in array in the form of MIDI note number. Is there an algorithm that would get me the key and scale of the song represented by these notes?

Answer

Michael Scott Cuthbert picture Michael Scott Cuthbert · Feb 7, 2013

If you're using Python you can use the music21 toolkit to do this:

import music21
score = music21.converter.parse('filename.mid')
key = score.analyze('key')
print(key.tonic.name, key.mode)

if you care about specific algorithms for key finding, you can use them instead of the generic "key":

key1 = score.analyze('Krumhansl')
key2 = score.analyze('AardenEssen')

etc. Any of these methods will work for chords also.

(Disclaimer: music21 is my project, so of course I have a vested interest in promoting it; but you can look at the music21.analysis.discrete module to take ideas from there for other projects/languages. If you have a MIDI parser, the Krumhansl algorithm is not hard to implement).