Created
March 26, 2024 10:42
-
-
Save sunpazed/cf1fd1a03e316600517bbc349e6b97ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function calculateCompression(audioData){ | |
// Convert the linear values to dB | |
let audioDataInDb = audioData.map(x => -20 * Math.log10(x || 1e-9)); // Avoid log(0) by replacing 0 with a very small number | |
// Compute the peak value | |
let peak = Math.max(...audioDataInDb); | |
// Compute the RMS value | |
let sumOfSquares = 0; | |
for (let i = 0; i < audioDataInDb.length; i++) { | |
sumOfSquares += audioDataInDb[i] * audioDataInDb[i]; | |
} | |
let rms = Math.sqrt(sumOfSquares / audioDataInDb.length); | |
// Calculate the difference between the peak and the RMS level | |
let compression = peak - rms; | |
return compression; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function calculateSNR(audioData){ | |
// Convert the linear values to dB | |
let ad = audioData.filter(x => (x>=0)); | |
let audioDataInDb = ad.map(x => -20 * Math.log10(x || 1e-9)); // Avoid log(0) by replacing 0 with a very small number | |
// Compute the mean value (signal power) | |
let signalPower = 0; | |
for (let i = 0; i < audioDataInDb.length; i++) { | |
signalPower += audioDataInDb[i] * audioDataInDb[i]; | |
} | |
signalPower /= audioDataInDb.length; | |
// Compute the variance (noise power) | |
let noisePower = 0; | |
let mean = signalPower / audioDataInDb.length; | |
for (let i = 0; i < audioDataInDb.length; i++) { | |
noisePower += Math.pow(audioDataInDb[i] - mean, 2); | |
} | |
noisePower /= audioDataInDb.length; | |
// Make sure we don't divide by zero | |
if (noisePower === 0) { | |
return Infinity; | |
} | |
// Compute the SNR in decibels | |
let snrDb = 10 * Math.log10(signalPower / noisePower); | |
return snrDb; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment