note-to-frequency
Version:
🎼 converts a note (scientific pitch notation) to a frequency
2 lines (1 loc) • 1.5 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.noteToFrequency=t()}(this,function(){"use strict";var e=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],t=function(t,n){return n="#",t=e[e.indexOf(t)-1].charAt(0),{signature:n,letter:t}},n=function(e){return"b"===e||"#"===e},r=function(e){return!Number.isNaN(e)},o=function(e){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=o.maxOctave,i=void 0===a?8:a,u=o.flatToSharp,f=void 0!==u&&u,v=o.octave,c=void 0!==v&&v,d=c?"1":"0,1",h=new RegExp("^(?!([EB]#)|([CF]b))([A-G]{1})([#|b]{0,1})([0-"+i+"]{"+d+"})$","ig");if(!h.test(e))throw new Error("'"+e+"' is not a valid note");for(var l=e.charAt(0),s="",g=void 0,p=1;p<e.length;p++){var b=e[p];n(b)&&(s=b),r(b)&&(g=parseInt(b))}if("b"===s&&f){var x=t(l,s);s=x.signature,l=x.letter}var A={letter:l,signature:s,octave:g};return Object.keys(A).forEach(function(e){return!A[e]&&delete A[e]}),A},a=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],i=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return t*a.length+a.indexOf(""+e+n)+1},u=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.base,r=void 0===n?440:n,a=t.maxOctave,u=void 0===a?8:a,f=o(e,{flatToSharp:!0,maxOctave:u,octave:!0}),v=f.letter,c=f.octave,d=f.signature,h=i(v,c,d),l=i("A",4),s=h-l,g=Math.pow(2,1/12);return Math.round(r*Math.pow(g,s)*100)/100};return u});