summaryrefslogtreecommitdiff
path: root/assets/js/normalizer.js
blob: ae3f830bc39a2350c5e71f915e5bcf2a1e8ae550 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
window.currentNormalizationContext = null;
window.currentNormalizationContext2 = null;
window.currentNormalizationContext3 = null;

function normalizeAudio(ab, gainBoost, stella) {
    ab = ab.slice(0);

    return new Promise((res) => {
        let currentNormalizationProfile = currentNormalizationContext.createGain();

        if (localStorage.getItem("noamp") !== "true" && !stella) {
            currentNormalizationProfile.gain.value = (1.0 + gainBoost) / 10.0 + 0.5;
        } else {
            currentNormalizationProfile.gain.value = (1.0 + gainBoost) / 10.0;
        }

        if (localStorage.getItem("normalize") === "false") res(currentNormalizationProfile);

        currentNormalizationContext.decodeAudioData(ab).then(function(decodedData) {
            let decodedBuffer = decodedData.getChannelData(0);
            let sliceLen = Math.floor(decodedData.sampleRate * 0.05);
            let averages = [];
            let sum = 0.0;

            for (let i = 0; i < decodedBuffer.length; i++) {
                sum += decodedBuffer[i] ** 2;
                if (i % sliceLen === 0) {
                    sum = Math.sqrt(sum / sliceLen);
                    averages.push(sum);
                    sum = 0;
                }
            }

            averages.sort(function(a, b) { return a - b; });
            let a = averages[Math.floor(averages.length * 0.95)];

            let gain = (1.0 + gainBoost) / a;
            gain = gain / 10.0;

            console.log("Calculated gain:", gain);

            if (localStorage.getItem("noamp") !== "true" && !stella) {
                currentNormalizationProfile.gain.value = gain + 0.5;
            } else {
                currentNormalizationProfile.gain.value = gain;
            }

            res(currentNormalizationProfile);
        });
    });
}