How do I transpose music chords using JavaScript?

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

    Just to expand on nnnnnn's answer. We can take his code and add a little bit more code to actually make it work with flats.

    transposeChord("F#sus7/A#", 1)
    > "Gsus7/B"
    
    transposeChord("Bb", 1)
    > "B"
    
    ... works like a charm
    

    function transposeChord(chord, amount) {
        var scale = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
        var normalizeMap = {"Cb":"B", "Db":"C#", "Eb":"D#", "Fb":"E", "Gb":"F#", "Ab":"G#", "Bb":"A#",  "E#":"F", "B#":"C"}
        return chord.replace(/[CDEFGAB](b|#)?/g, function(match) {
            var i = (scale.indexOf((normalizeMap[match] ? normalizeMap[match] : match)) + amount) % scale.length;
            return scale[ i < 0 ? i + scale.length : i ];
        })
    }
    
    Chord:         
    transposed by  
    =             
                  

提交回复
热议问题