Last active
September 4, 2018 14:33
-
-
Save chrisburnell/012eeb692711fdb54e938254a2b93944 to your computer and use it in GitHub Desktop.
JavaScript function(s) to convert a run of piano keys into their respective frequencies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//// | |
/// Return a frequency based on piano key | |
/// @param {Number} key [49] | |
/// @return {Number} frequency | |
//// | |
let getFrequencyFromKey = (key = 49) => { | |
return 2 ** ((key - 49) / 12) * 440; | |
}; | |
//// | |
/// Convert a string-based key to a number-based key | |
//// | |
let convertKeyStringToNumber = (key = "C4") => { | |
let series = key.match(/\d/g)[0]; | |
let notes = ["A", "A#Bb", "B", "C", "C#Db", "D", "D#Eb", "E", "F", "F#Gb", "G", "G#Ab"]; | |
let note = key.replace(/\d/g, ''); | |
return (note.match(/[AB]/) ? series : series - 1) * 12 + notes.indexOf(note) + 1; | |
}; | |
//// | |
/// Return an array of frequencies from a starting key, array of semitone | |
/// intervals, and number of keys to convert. | |
/// @param {Number} keyStart [41] Middle C | |
/// @param {Array} keyIntervals [[0]] | |
/// @param {Number} keyCount [1] | |
/// @return {Array} frequencies | |
//// | |
let getFrequenciesFromKeys = (keyStart = 41, keyIntervals = [0], keyCount = 1) => { | |
let frequencies = [getFrequencyFromKey(keyStart)]; | |
let keyInterval = 0; | |
for (let count = 1; count < keyCount; count++) { | |
keyInterval += Number.parseFloat(keyIntervals[count % keyIntervals.length]); | |
frequencies.push(getFrequencyFromKey(keyStart + keyInterval)); | |
} | |
return frequencies; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment