Last active 1 week ago

chrisburnell's Avatar chrisburnell revised this gist 1 week ago. Go to revision

1 file changed, 39 insertions

keys-to-frequencies.js(file created)

@@ -0,0 +1,39 @@
1 + ////
2 + /// Return a frequency based on piano key
3 + /// @param {Number} key [49]
4 + /// @return {Number} frequency
5 + ////
6 + const getFrequencyFromKey = (key = 49) => {
7 + return 2 ** ((key - 49) / 12) * 440;
8 + };
9 +
10 + ////
11 + /// Convert a string-based key to a number-based key
12 + ////
13 + const convertKeyStringToNumber = (key = "C4") => {
14 + let series = key.match(/\d/g)[0];
15 + let notes = ["A", "A#Bb", "B", "C", "C#Db", "D", "D#Eb", "E", "F", "F#Gb", "G", "G#Ab"];
16 + let note = key.replace(/\d/g, '');
17 +
18 + return (note.match(/[AB]/) ? series : series - 1) * 12 + notes.indexOf(note) + 1;
19 + };
20 +
21 + ////
22 + /// Return an array of frequencies from a starting key, array of semitone
23 + /// intervals, and number of keys to convert.
24 + /// @param {Number} keyStart [41] Middle C
25 + /// @param {Array} keyIntervals [[0]]
26 + /// @param {Number} keyCount [1]
27 + /// @return {Array} frequencies
28 + ////
29 + const getFrequenciesFromKeys = (keyStart = 41, keyIntervals = [0], keyCount = 1) => {
30 + let frequencies = [getFrequencyFromKey(keyStart)];
31 + let keyInterval = 0;
32 +
33 + for (let count = 1; count < keyCount; count++) {
34 + keyInterval += Number.parseFloat(keyIntervals[count % keyIntervals.length]);
35 + frequencies.push(getFrequencyFromKey(keyStart + keyInterval));
36 + }
37 +
38 + return frequencies;
39 + };
Newer Older