title: How to calculate the level/amplitude/db of audio signal in java?
body: <p>I want to create a audio level meter in java for the microphone to check how loud the input is. It should look like the one of the OS. I'm not asking about the gui. It is just about calculating the audio level out of the bytestream produced by </p>
  
  <pre><code>n = targetDataLine.read( tempBuffer , 0 , tempBuffer.length );
  </code></pre>
  
  <p>So I already have something that is running, but it is not even close to the levelmeter of my OS (windows) It stucks in the middle. I have values between 0 and 100 that is good but in the middle volume it stucks around 60 no matter how loud the input is.</p>
  
  <p>This is how I calculate it now:</p>
  
  <pre><code>            amplitude = 0;
          for (int j = 0; j &lt; tempBuffer.length; j = j +2 ){
              if (tempBuffer[j] &gt; tempBuffer[j+1])
                  amplitude = amplitude + tempBuffer[j] - tempBuffer[j+1];
              else amplitude = amplitude + tempBuffer[j + 1] - tempBuffer[j];
          }
          amplitude = amplitude / tempBuffer.length * 2;
  </code></pre>
  
  <p>Is there a better/more precise way to calculate the audio level to monitor it? Or did I maybe do a major mistake?</p>
  
  <p>That is my Audioformat:</p>
  
  <pre><code>public static AudioFormat getAudioFormat(){
      float sampleRate = 20000.0F;
      //8000,11025,16000,22050,44100
      int sampleSizeInBits = 16;
      //8,16
      int channels = 1;
      //1,2
      boolean signed = true;
      //true,false
      boolean bigEndian = false;
      //true,false
      return new AudioFormat( sampleRate, sampleSizeInBits, channels, signed, bigEndian );
      //return new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000.0F, 8, 1, 1, 8000.0F, false);
  }
  </code></pre>