Skip to content

Instantly share code, notes, and snippets.

@jcurtis-cc
Created February 9, 2023 09:33
Show Gist options
  • Select an option

  • Save jcurtis-cc/c2eb2909c3454ae2a9a69ea53d3264e7 to your computer and use it in GitHub Desktop.

Select an option

Save jcurtis-cc/c2eb2909c3454ae2a9a69ea53d3264e7 to your computer and use it in GitHub Desktop.
JavaScript functions for music related conversions
let pitchclassToKeyString = function(k) {
ks = Math.floor(k/2);
ks += (k > 4 && k%2 == 1) ? 1 : 0;
ks %= 5; ks += k > 8 ? 65 : 67;
var keystr = String.fromCharCode(ks);
keystr += ((k<5 && k%2==1)||(k>5&&k%2==0)) ? "#" : "";
return keystr
}
let keyStringToPitchclass = function(k) {
const acc = k[1] == "#" ? "sharp" : k[1] == "b" ? "flat" : "natural";
let pc = (((k.charCodeAt(0) - 53) % 7) * 2); pc += pc > 4 ? -1 : 0;
pc += acc === "sharp" ? 1 : acc === "flat" ? -1 : 0;
pc %= 12; pc += pc < 0 ? 12 : 0;
return pc
}
let midiToFrequency = function(midinote) {
return 440.0 * Math.pow( 2.0, (midinote - 69.0) / 12.0 );
}
let frequencyToMidi = function(freq) {
return 12 * Math.log2(freq/440) + 69; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment