title: Change an audio stream's volume by changing bytes directly
body: <p>For a peer-to-peer audio client, I need to have the ability to change the output volume to a desired level. In my case, the volume is a floating point number between zero and one.</p>
  
  <p>I modify the audio stream this way:</p>
  
  <pre><code>void play(byte[] buf)
  {
      for (int i = 0; i &lt; buf.length; i += 2)
      {
          // sample size is 2 bytes, so convert to int and then back
          int data = ((buf[i + 1] &amp; 0xFF) &lt;&lt; 8) | (buf[i] &amp; 0xFF);
          data = (int) (data * outputVolume);
          buf[i] = (byte) (data &amp; 0xFF);
          buf[i + 1] = (byte) (data &gt;&gt; 8);
      }
      line.write(buf, 0, Math.min(buf.length, line.available()));
  }
  </code></pre>
  
  <p>Now, when <code>outputVolume</code> is set to 0, the output is silent. When it is set to 1, it behaves normal and quality is fine (as it is not modified). But any numbers between 0 and 1 produce a horrible noise which is louder than the expected stream itself. At 0.5, the noise reaches it's loudest point.</p>
  
  <p>I don't want to use the controls of the audio mixer itself (like gain control or volume control) because I had compatibility problems this way and later on, I want to modify the byte stream even more so I have to iterate through the stream anyway.</p>