Files
rsgp/src/lib/audio/processors/Normalize.ts

44 lines
1.1 KiB
TypeScript

import type { AudioProcessor, ProcessorCategory } from "./AudioProcessor";
export class Normalize implements AudioProcessor {
getName(): string {
return "Normalize";
}
getDescription(): string {
return "Normalizes audio to maximum amplitude without clipping";
}
getCategory(): ProcessorCategory {
return 'Amplitude';
}
async process(
leftChannel: Float32Array,
rightChannel: Float32Array
): Promise<[Float32Array, Float32Array]> {
let maxAmplitude = 0;
for (let i = 0; i < leftChannel.length; i++) {
maxAmplitude = Math.max(maxAmplitude, Math.abs(leftChannel[i]));
maxAmplitude = Math.max(maxAmplitude, Math.abs(rightChannel[i]));
}
if (maxAmplitude === 0) {
return [leftChannel, rightChannel];
}
const gain = 1.0 / maxAmplitude;
const newLeft = new Float32Array(leftChannel.length);
const newRight = new Float32Array(rightChannel.length);
for (let i = 0; i < leftChannel.length; i++) {
newLeft[i] = leftChannel[i] * gain;
newRight[i] = rightChannel[i] * gain;
}
return [newLeft, newRight];
}
}