ChordSheetJS icon indicating copy to clipboard operation
ChordSheetJS copied to clipboard

How to detect the current key?

Open gpr19 opened this issue 1 year ago • 4 comments

Is there any way to detect which key a song is in?

gpr19 avatar Dec 14 '23 13:12 gpr19

Hey @gpr19. Thanks for reaching out.

Unless the current key is set in the song (either in chordpro or programmatically), there is no way to get the song key.

You could probably implement something to guess the song key, but it is not a current or planned feature.

martijnversluis avatar Dec 14 '23 16:12 martijnversluis

Few years ago I wrote my own chordpro library in which I implemented a basic key guesser system. I plan to join the development of this library since it looks great now.

There are techniques like checking the first and last chord of the song, taking the most use chord,...

I will try to implement that in the future (when I have more time).

edwinzap avatar Feb 06 '24 08:02 edwinzap

Wow, sounds great @edwinzap! Looking forward to your contributions, and thanks for reaching out! 👍

martijnversluis avatar Feb 14 '24 20:02 martijnversluis

With the help of chatGPT I managed to create a function that works temporarily for me.

function:

function determineKey(chords) {
    // Create an object to count the frequency of each note
    const frequencyChords = {};

    // Iterate over the note array and count the frequency of each note
    chords.forEach(chord => {
        if (frequencyChords[chord]) {
          frequencyChords[chord]++;
        } else {
          frequencyChords[chord] = 1;
        }
    });

    // Find the note with the highest frequency
    let key = '';
    let maxFrequency = 0;
    Object.keys(frequencyChords).forEach(chord => {
        if (frequencyChords[chord] > maxFrequency) {
            key = chord;
            maxFrequency = frequencyChords[chord];
        }
    });

    return key;
}

Use:

const song = new ChordSheetJS.ChordProParser().parse(chordSheet)
let chords = []
let key
if (!song.key){
    song.mapItems((item) => {
      if (item instanceof ChordLyricsPair) {
        if (item.chords) {
          chords.push(item.chords)
        }
      }
    })
    key = determineKey(chords)
}

gpr19 avatar Apr 17 '24 19:04 gpr19