How do I transpose music chords using JavaScript?

前端 未结 7 1362
忘掉有多难
忘掉有多难 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:51

    How about a little somethin' like this:

    function transposeChord(chord, amount) {
      var scale = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
      return chord.replace(/[CDEFGAB]#?/g,
                           function(match) {
                             var i = (scale.indexOf(match) + amount) % scale.length;
                             return scale[ i < 0 ? i + scale.length : i ];
                           });
    }
    
    alert(transposeChord("Dm7/G", 2)); // gives "Em7/A"
    alert(transposeChord("Fmaj9#11", -23)); // gives "F#maj9#11"
    

    Note that I threw in the "F#maj9#11" example just to give you more to think about with regard to what makes up a valid chord name: you may find a "#" sharp symbol that doesn't follow a letter (in this case it belongs to the "11").

    And, obviously, my function only understands sharps, not flats, and doesn't understand keys, so, e.g., transposeChord("C/E", 1) will give "C#/F" when it really should be "C#/E#".

    0 讨论(0)
提交回复
热议问题