How do I transpose music chords using JavaScript?

前端 未结 7 1517
忘掉有多难
忘掉有多难 2021-02-08 08:56

I was wondering how would one create a javascript function for transposing music chords.

Since I don\'t expect everyone to be a musician here, I\'ll try to explain how i

7条回答
  •  耶瑟儿~
    2021-02-08 09:37

    Define your keys with an object:

    var keys = ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"];
    

    Parse your chord with a regular expression:

    var matches = /([A-G]#?)([^\/]*)(?:\/([A-G]#?))?/.exec(chord);
    var key = matches[1];
    var descriptor = matches[2];
    var bass = matches[3];
    

    Do a little math to get the new key:

    var newKey = keys[(keys.indexOf(key) + transpose) % keys.length];
    var newBass = keys[(keys.indexOf(bass) + transpose) % keys.length];
    

    Put it all back together again:

    var newChord = newKey + descriptor;
    if (newBass) {
        newChord += "/" + newBass;
    }
    return newChord;
    

提交回复
热议问题