skip to Main Content

Hi i’m facing a problem with respect to decibel convertion

Question: html5 volume accepted range is between 0 – 1 now how to convert decibel value i,e between -96 to 96 into 0-1.

Here is what i have tried:

  function linearToDecibel(linearValue) {
      // Convert linear value to decibels
      var decibelValue = 20 * Math.log10(linearValue);
      return decibelValue;
   }

  console.log(linearToDecibel(96)) // my expection is value 1 or 100%

   

Further conversion i dont know please help me.

2

Answers


  1. To convert -96 -> 96 on a range of 0 -> 1 you can

    (x + 96) / (96 * 2)

    And you can simplify by

    (x + 96) / 192

    Login or Signup to reply.
  2. You can normalize the value based on the fromRange, and then scale it to the toRange.

    /**
     * Normalizes and scales a number from one range to another.
     * @param {number} value - value to scale
     * @param {number[]} fromRange - source range [min, max] (inclusive)
     * @param {number[]} toRange - target range [min, max] (inclusive)
     * @returns {number} A scaled value respective of the toRange
     */
    const scaleValue = (value, fromRange, toRange) =>
      (value - fromRange[0]) *
      (toRange[1] - toRange[0]) /
      (fromRange[1] - fromRange[0]) +
      toRange[0];
    
    /**
     * Convert a decibel value to a percentage.
     * @param {number} decibelVal - decibel value to scale to linear
     * @returns {number} A value between [0.0, 1.0]
     */
    const decibelToLinear = (decibelVal) => scaleValue(decibelVal, [-96, 96], [0, 1]);
    
    /**
     * Convert a percentage value to a decibel value.
     * @param {number} linearVal - linear value to scale to decibel
     * @returns {number} A value between [-95, 95]
     */
    const linearToDecibel = (linearVal) => scaleValue(linearVal, [0, 1], [-96, 96]);
    
    console.log(decibelToLinear(-96)); // 0.0  or    0%
    console.log(decibelToLinear(0));   // 0.5  or   50%
    console.log(decibelToLinear(96));  // 1.0  or  100%
    
    console.log(linearToDecibel(0.0)); // -96
    console.log(linearToDecibel(0.5)); //   0
    console.log(linearToDecibel(1.0)); //  96
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search