Created
January 18, 2017 15:33
-
-
Save below9k/cf17e10341cb5c61a03a53a64cc35fb2 to your computer and use it in GitHub Desktop.
Convert range of decibel to percentage and back again
This file contains hidden or 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
| // I wrote this to convert dB to percentage with a weird scale. | |
| // For instance, a user may set an amplifier's min-max dB limits to -50 - 10. | |
| // The UI they use only increments by 1 and dB does not (properly) scale linearly. | |
| // Having to work around these issues I wrote this based on the script I found here www.redwirez.com/pcalc.jsp | |
| // =-=-=-=-=-=-=-= | |
| // Calcs dB to percent with a non-standard dB range | |
| // it does this by getting a new percentage range using min/max dB | |
| // defaults to the standard range of -80 ~ 0 if no min or max is provided | |
| const calcDb = (perc, minDb, maxDb, minP, maxP) => { | |
| const getPerc = (db) => (Math.round(1000000000 * Math.pow(10, db / 20)) / 10000000) | |
| const maxPerc = maxP || (_.isNumber(maxDb) && getPerc(maxDb)) || 100 | |
| const minPerc = minP || (_.isNumber(minDb) && getPerc(minDb)) || 0 | |
| const range = maxPerc - minPerc | |
| const newPerc = (range / 100) * perc | |
| return Math.round(1000000000 * 20 * (Math.log(newPerc * 0.01) / Math.log(10))) / 1000000000 | |
| } | |
| // Calcs percentage to dB with a non-standard dB range | |
| // leverages calcDb to scale to the new range | |
| // defaults to 0 - 100 min or max percent/dB if they are not provided | |
| const calcPerc = (dB, minDb, maxDb, minP, maxP) => { | |
| const getPerc = (db) => (Math.round(1000000000 * Math.pow(10, db / 20)) / 10000000) | |
| const maxPerc = maxP || (_.isNumber(maxDb) && getPerc(maxDb)) || 100 | |
| const minPerc = minP || (_.isNumber(minDb) && getPerc(minDb)) || 0 | |
| const range = maxPerc - minPerc | |
| const newDb = calcDb((getPerc(dB) / range) * 100, null, null, minPerc, maxPerc) | |
| return Math.round(1000000000 * Math.pow(10, newDb / 20)) / 10000000 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment