How do I transpose music chords using JavaScript?

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

    function transpose(chord, increment)
    {
        var cycle = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
        var el = chord.charAt(0);
        if(chord.length > 1 && chord.charAt(1) == '#')
        {
            el += "#";   
        }
        var ind = cycle.indexOf(el);
        var newInd = (ind + increment + cycle.length) % cycle.length;
        var newChord = cycle[newInd];
        return newChord + chord.substring(el.length);
    }
    

    I'll let you figure out the bass part, since it's really just calling the function twice.

    Also, you can add the code here before the function for old browsers that don't support indexOf.

    I put a demo on jsFiddle.

    EDIT: The issue was with negative modulus. The above will work as long as long as the negative isn't more than the length (e.g. you can't transpose 100 steps down).

提交回复
热议问题