Normalizer { public double normalize(double[] audioSample, float sampleRate) { double max = Double.MIN_VALUE; for (int i = 0; i < audioSample.length; i++) { double abs = Math.abs(audioSample[i]); if (abs > max) { max = abs; } } if(max > 1.0d) { throw new IllegalArgumentException("Expected value for audio are in the range -1.0 <= v <= 1.0 "); } if (max < 5 * Math.ulp(0.0d)) { return 1.0d; } for (int i = 0; i < audioSample.length; i++) { audioSample[i] /= max; } return 1.0d / max; }  double normalize(double[] audioSample, float sampleRate);  }
@Test public void normalizingValuesContainingOneIsANoOp() { Arrays.fill(values, 0.1d); values[10] = 1.0d; double[] values2 = Arrays.copyOf(values, values.length); double gainMultiplier = normalizer.normalize(values, 22050.0f); assertThat(gainMultiplier, is(equalTo(1.0d))); assertThat(values, is(equalTo(values2))); }
@Test public void normalizingValuesContainingMinusOneIsANoOp() { Arrays.fill(values, 0.1d); values[10] = -1.0d; double[] values2 = Arrays.copyOf(values, values.length); double gainMultiplier = normalizer.normalize(values, 22050.0f); assertThat(gainMultiplier, is(equalTo(1.0d))); assertThat(values, is(equalTo(values2))); }
@Test public void normalizingValuesContainingOnlyZeroesIsANoOp() { double[] values2 = Arrays.copyOf(values, values.length); double gainMultiplier = normalizer.normalize(values, 22050.0f); assertThat(gainMultiplier, is(closeTo(1.0d, Math.ulp(0.0d)))); assertThat(values, is(equalTo(values2))); }
@Test public void normalizingValuesContainingEightTenths() { Arrays.fill(values, 0.1d); values[10] = 0.8d; double gainMultiplier = normalizer.normalize(values, 22050.0f); assertThat(gainMultiplier, is(equalTo(1.25d))); for(int i = 0; i < values.length; i++) { if(i != 10) { assertThat(values[i], is(equalTo(0.125d))); } else { assertThat(values[10], is(equalTo(1.0d))); } } }