const getNormalizedAudioBuffer = (inputBuffer: AudioBuffer) => {
  const normalizedBuffer = new AudioBuffer({
    sampleRate: inputBuffer.sampleRate,
    length: inputBuffer.length,
    numberOfChannels: inputBuffer.numberOfChannels,
  });

  let maxSample = 0;
  for (let i = 0; i < inputBuffer.numberOfChannels; i++) {
    const samples = inputBuffer.getChannelData(i);
    for (let j = 0; j < samples.length; j++) {
      maxSample = Math.max(maxSample, Math.abs(samples[j]));
    }
  }

  for (let i = 0; i < inputBuffer.numberOfChannels; i++) {
    const inputSamples = inputBuffer.getChannelData(i);
    const normalizedSamples = normalizedBuffer.getChannelData(i);
    for (let j = 0; j < inputSamples.length; j++) {
      normalizedSamples[j] = inputSamples[j] / maxSample;
    }
  }

  return normalizedBuffer;
};

export default getNormalizedAudioBuffer;
