title: Audio: Change Volume of samples in byte array
body: <p>I'm reading a wav-file to a byte array using <a href="http://snippi.com/s/ndi3f4x">this method (shown below)</a>. Now that I have it stored inside my byte array, I want to change the sounds volume.</p>
  
  <pre><code>private byte[] getAudioFileData(final String filePath) {
      byte[] data = null;
      try {
      final ByteArrayOutputStream baout = new ByteArrayOutputStream();
      final File file = new File(filePath);
      final AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
  
      byte[] buffer = new byte[4096];
      int c;
      while ((c = audioInputStream.read(buffer, 0, buffer.length)) != -1) {
          baout.write(buffer, 0, c);
      }
      audioInputStream.close();
      baout.close();
      data = baout.toByteArray();
      } catch (Exception e) {
      e.printStackTrace();
      }
      return data;
  }
  </code></pre>
  
  <p><strong>Edit:</strong> Per request some info on the audio format:</p>
  
  <blockquote>
    <p>PCM_SIGNED 44100.0 Hz, 16 bit, mono, 2 bytes/frame, little-endian</p>
  </blockquote>
  
  <p>From physics-class I remembered that you can change the amplitude of a sine-wave by multiplying the sine-value with a number between 0 and 1.</p>
  
  <p><strong>Edit: Updated code for 16-bit samples:</strong></p>
  
  <pre><code>private byte[] adjustVolume(byte[] audioSamples, double volume) {
      byte[] array = new byte[audioSamples.length];
      for (int i = 0; i &lt; array.length; i+=2) {
          // convert byte pair to int
          int audioSample = (int) ((audioSamples[i+1] &amp; 0xff) &lt;&lt; 8) | (audioSamples[i] &amp; 0xff);
  
          audioSample = (int) (audioSample * volume);
  
          // convert back
          array[i] = (byte) audioSample;
          array[i+1] = (byte) (audioSample &gt;&gt; 8);
  
      }
      return array;
  }
  </code></pre>
  
  <p>The sound is heavily distorted if I multiply <code>audioSample</code> with <code>volume</code>. If I don't and compare both arrays with <code>Arrays.compare(array, audioSample)</code> I can conclude that the byte-array is being converted correctly to int and the other way around.</p>
  
  <p>Can anybody help me out? What am I getting wrong here? Thank you! :)</p>