HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<div id="container"><canvas id="canvas"></canvas></div>
<audio id="audio" controls crossorigin></audio>
<input id="audioFileInput" type="file" accept="audio/*">
<script>
function map(x, min, max, targetMin, targetMax) {
return (x - min) / (max - min) * (targetMax - targetMin) + targetMin;
}
function clamp(x, min, max) {
return Math.min(Math.max(x, min), max);
}
function idxWrapOver(x, length) {
return (x % length + length) % length;
}
// Hz and FFT bin conversion
function hertzToFFTBin(x, y = 'round', bufferSize = 4096, sampleRate = 44100) {
const bin = x * bufferSize / sampleRate;
let func = y;
if (!['floor','ceil','trunc'].includes(func))
func = 'round'; // always use round if you specify an invalid/undefined value
return Math[func](bin);
}
function fftBinToHertz(x, bufferSize = 4096, sampleRate = 44100) {
return x * sampleRate / bufferSize;
}
// Calculate the FFT
function calcFFT(input) {
let fft = input.map(x => x);
let fft2 = input.map(x => x);
transform(fft, fft2);
let output = new Array(Math.round(fft.length/2)).fill(0);
for (let i = 0; i < output.length; i++) {
output[i] = Math.hypot(fft[i], fft2[i])/(fft.length);
}
return output;
}
function calcComplexFFT(input) {
let fft = input.map(x => x);
let fft2 = input.map(x => x);
transform(fft, fft2);
return input.map((_, i, arr) => {
return {
re: fft[i]/(arr.length/2),
im: fft2[i]/(arr.length/2),
magnitude: Math.hypot(fft[i], fft2[i])/(arr.length/2),
phase: Math.atan2(fft2[i], fft[i])
};
});
}
function calcComplexInputFFT(real, imag) {
if (real.length !== imag.length)
return [];
const fft1 = real.map(x => x),
fft2 = imag.map(x => x);
transform(fft1, fft2);
return real.map((_, i, arr) => {
return {
re: fft1[i]/arr.length,
im: fft2[i]/arr.length,
magnitude: Math.hypot(fft1[i], fft2[i])/arr.length,
phase: Math.atan2(fft2[i], fft1[i])
}
});
}
/**
* FFT and convolution (JavaScript)
*
* Copyright (c) 2017 Project Nayuki. (MIT License)
* https://www.nayuki.io/page/free-small-fft-in-multiple-languages
*/
/*
* Computes the discrete Fourier transform (DFT) of the given complex vector, storing the result back into the vector.
* The vector can have any length. This is a wrapper function.
*/
function transform(real, imag) {
const n = real.length;
if (n != imag.length)
throw "Mismatched lengths";
if (n <= 0)
return;
else if ((2 ** Math.trunc(Math.log2(n))) === n) // Is power of 2
transformRadix2(real, imag);
else // More complicated algorithm for arbitrary sizes
transformBluestein(real, imag);
}
/*
* Computes the inverse discrete Fourier transform (IDFT) of the given complex vector, storing the result back into the vector.
* The vector can have any length. This is a wrapper function. This transform does not perform scaling, so the inverse is not a true inverse.
*/
function inverseTransform(real, imag) {
transform(imag, real);
}
/*
* Computes the discrete Fourier transform (DFT) of the given complex vector, storing the result back into the vector.
* The vector's length must be a power of 2. Uses the Cooley-Tukey decimation-in-time radix-2 algorithm.
*/
function transformRadix2(real, imag) {
// Length variables
const n = real.length;
if (n != imag.length)
throw "Mismatched lengths";
if (n <= 1) // Trivial transform
return;
const logN = Math.log2(n);
if ((2 ** Math.trunc(logN)) !== n)
throw "Length is not a power of 2";
// Trigonometric tables
let cosTable = new Array(n / 2);
let sinTable = new Array(n / 2);
for (let i = 0; i < n / 2; i++) {
cosTable[i] = Math.cos(2 * Math.PI * i / n);
sinTable[i] = Math.sin(2 * Math.PI * i / n);
}
// Bit-reversed addressing permutation
for (let i = 0; i < n; i++) {
let j = reverseBits(i, logN);
if (j > i) {
let temp = real[i];
real[i] = real[j];
real[j] = temp;
temp = imag[i];
imag[i] = imag[j];
imag[j] = temp;
}
}
// Cooley-Tukey decimation-in-time radix-2 FFT
for (let size = 2; size <= n; size *= 2) {
let halfsize = size / 2;
let tablestep = n / size;
for (let i = 0; i < n; i += size) {
for (let j = i, k = 0; j < i + halfsize; j++, k += tablestep) {
const l = j + halfsize;
const tpre = real[l] * cosTable[k] + imag[l] * sinTable[k];
const tpim = -real[l] * sinTable[k] + imag[l] * cosTable[k];
real[l] = real[j] - tpre;
imag[l] = imag[j] - tpim;
real[j] += tpre;
imag[j] += tpim;
}
}
}
// Returns the integer whose value is the reverse of the lowest 'bits' bits of the integer 'x'.
function reverseBits(x, bits) {
let y = 0;
for (let i = 0; i < bits; i++) {
y = (y << 1) | (x & 1);
x >>>= 1;
}
return y;
}
}
/*
* Computes the discrete Fourier transform (DFT) of the given complex vector, storing the result back into the vector.
* The vector can have any length. This requires the convolution function, which in turn requires the radix-2 FFT function.
* Uses Bluestein's chirp z-transform algorithm.
*/
function transformBluestein(real, imag) {
// Find a power-of-2 convolution length m such that m >= n * 2 + 1
const n = real.length;
if (n != imag.length)
throw "Mismatched lengths";
const m = 2 ** Math.trunc(Math.log2(n*2)+1);
// Trignometric tables
let cosTable = new Array(n);
let sinTable = new Array(n);
for (let i = 0; i < n; i++) {
let j = i * i % (n * 2); // This is more accurate than j = i * i
cosTable[i] = Math.cos(Math.PI * j / n);
sinTable[i] = Math.sin(Math.PI * j / n);
}
// Temporary vectors and preprocessing
let areal = newArrayOfZeros(m);
let aimag = newArrayOfZeros(m);
for (let i = 0; i < n; i++) {
areal[i] = real[i] * cosTable[i] + imag[i] * sinTable[i];
aimag[i] = -real[i] * sinTable[i] + imag[i] * cosTable[i];
}
let breal = newArrayOfZeros(m);
let bimag = newArrayOfZeros(m);
breal[0] = cosTable[0];
bimag[0] = sinTable[0];
for (let i = 1; i < n; i++) {
breal[i] = breal[m - i] = cosTable[i];
bimag[i] = bimag[m - i] = sinTable[i];
}
// Convolution
let creal = new Array(m);
let cimag = new Array(m);
convolveComplex(areal, aimag, breal, bimag, creal, cimag);
// Postprocessing
for (let i = 0; i < n; i++) {
real[i] = creal[i] * cosTable[i] + cimag[i] * sinTable[i];
imag[i] = -creal[i] * sinTable[i] + cimag[i] * cosTable[i];
}
}
/*
* Computes the circular convolution of the given real vectors. Each vector's length must be the same.
*/
function convolveReal(x, y, out) {
const n = x.length;
if (n != y.length || n != out.length)
throw "Mismatched lengths";
convolveComplex(x, newArrayOfZeros(n), y, newArrayOfZeros(n), out, newArrayOfZeros(n));
}
/*
* Computes the circular convolution of the given complex vectors. Each vector's length must be the same.
*/
function convolveComplex(xreal, ximag, yreal, yimag, outreal, outimag) {
const n = xreal.length;
if (n != ximag.length || n != yreal.length || n != yimag.length
|| n != outreal.length || n != outimag.length)
throw "Mismatched lengths";
xreal = xreal.slice();
ximag = ximag.slice();
yreal = yreal.slice();
yimag = yimag.slice();
transform(xreal, ximag);
transform(yreal, yimag);
for (let i = 0; i < n; i++) {
const temp = xreal[i] * yreal[i] - ximag[i] * yimag[i];
ximag[i] = ximag[i] * yreal[i] + xreal[i] * yimag[i];
xreal[i] = temp;
}
inverseTransform(xreal, ximag);
for (let i = 0; i < n; i++) { // Scaling (because this FFT implementation omits it)
outreal[i] = xreal[i] / n;
outimag[i] = ximag[i] / n;
}
}
function newArrayOfZeros(n) {
let result = new Array(n).fill(0);
return result;
}
</script>
body {
margin: 0;
overflow: hidden;
}
audio {
display: inline-block;
width: 100%;
height: 40px;
}
canvas {
display: block;
width: 100%;
}
#container {
height: calc( 100vh - 40px );
}
#upload {
display: none;
}
// necessary parts for audio context and audio elements respectively
const audioCtx = new AudioContext();
const audioPlayer = document.getElementById('audio');
const localAudioElement = document.getElementById('audioFileInput');
localAudioElement.addEventListener('change', loadLocalFile);
// canvas is for displaying visuals
const canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
container = document.getElementById('container');
const audioSource = audioCtx.createMediaElementSource(audioPlayer);
const analyser = audioCtx.createAnalyser();
analyser.fftSize = 32768; // maxes out FFT size
const dataArray = new Float32Array(analyser.fftSize);
// variables
/*
const currentSpectrum = [],
peaks = [],
peakHolds = [],
peakAccels = [];
*/
const delay = audioCtx.createDelay();
audioSource.connect(delay);
delay.connect(audioCtx.destination);
//audioSource.connect(audioCtx.destination);
audioSource.connect(analyser);
const visualizerSettings = {
fftSize: 4096,
showCentroid: true,
showSpread: true,
showRolloff: true,
showRolloff2: true,
showRolloff3: true,
rolloffThreshold: 99,
rolloffThreshold2: 50,
rolloffThreshold3: 1,
showFlatness: true,
showKurtosis: true,
showSkewness: true,
showSlope: true,
showCrest: true,
showSpectrum: true,
useWrongWay: false,
freeze: false,
darkMode: false,
compensateDelay: true
},
placeholderListData = {
'Option 1': 'one',
'Option 2': 'two'
}, // useful for multiple options sharing dropdown menu options
loader = {
url: '',
load: function() {
audioPlayer.src = this.url;
audioPlayer.play();
},
loadLocal: function() {
localAudioElement.click();
},
toggleFullscreen: _ => {
if (document.fullscreenElement === canvas)
document.exitFullscreen();
else
canvas.requestFullscreen();
}
};
// dat.GUI for quick customization
let gui = new dat.GUI();
gui.add(loader, 'url').name('URL');
gui.add(loader, 'load').name('Load');
gui.add(loader, 'loadLocal').name('Load from local device');
let settings = gui.addFolder('Visualization settings');
// FFT size can be non-power of 2 because we use the FFT library that supports non-power of two data length
settings.add(visualizerSettings, 'fftSize', 32, 32768, 1).name('FFT size');
// The additional parameters goes here
settings.add(visualizerSettings, 'showCentroid').name('Show centroid');
settings.add(visualizerSettings, 'showSpread').name('Show spread');
settings.add(visualizerSettings, 'showRolloff').name('Show rolloff 1');
settings.add(visualizerSettings, 'showRolloff2').name('Show rolloff 2');
settings.add(visualizerSettings, 'showRolloff3').name('Show rolloff 3');
settings.add(visualizerSettings, 'rolloffThreshold', 0, 100).name('Spectral rolloff threshold 1');
settings.add(visualizerSettings, 'rolloffThreshold2', 0, 100).name('Spectral rolloff threshold 2');
settings.add(visualizerSettings, 'rolloffThreshold3', 0, 100).name('Spectral rolloff threshold 3');
settings.add(visualizerSettings, 'showFlatness').name('Show flatness');
settings.add(visualizerSettings, 'showKurtosis').name('Show kurtosis');
settings.add(visualizerSettings, 'showSkewness').name('Show skewness');
settings.add(visualizerSettings, 'showSlope').name('Show slope');
settings.add(visualizerSettings, 'showCrest').name('Show crest');
settings.add(visualizerSettings, 'showSpectrum').name('Show spectrum visualization');
// another parameters at the end
settings.add(visualizerSettings, 'useWrongWay').name('Use full FFT data for spectral descriptors instead of N/2');
settings.add(visualizerSettings, 'freeze').name('Freeze analyzer');
settings.add(visualizerSettings, 'darkMode').name('Dark mode');
settings.add(visualizerSettings, 'compensateDelay').name('Compensate for delay');
gui.add(loader, 'toggleFullscreen').name('Toggle fullscreen mode');
function resizeCanvas() {
const scale = devicePixelRatio,
isFullscreen = document.fullscreenElement === canvas;
canvas.width = (isFullscreen ? innerWidth : container.clientWidth)*scale;
canvas.height = (isFullscreen ? innerHeight : container.clientHeight)*scale;
}
addEventListener('click', () => {
if (audioCtx.state == 'suspended')
audioCtx.resume();
});
addEventListener('resize', resizeCanvas);
resizeCanvas();
function loadLocalFile(event) {
const file = event.target.files[0],
reader = new FileReader();
reader.onload = (e) => {
audioPlayer.src = e.target.result;
audioPlayer.play();
};
reader.readAsDataURL(file);
}
visualize();
function visualize() {
delay.delayTime.value = (visualizerSettings.fftSize / audioCtx.sampleRate) * visualizerSettings.compensateDelay;
if (!visualizerSettings.freeze) {
// we use getFloatTimeDomainData (which is PCM data that is gathered, just like vis_stream::get_chunk_absolute() in foobar2000 SDK)
analyser.getFloatTimeDomainData(dataArray);
}
const fftData = new Array(visualizerSettings.fftSize);
let norm = 0; // we can use a variable called norm to compensate for gain changes incurred by a window function
for (let i = 0; i < visualizerSettings.fftSize; i++) {
const magnitude = dataArray[i+analyser.fftSize-visualizerSettings.fftSize],
w = applyWindow(map(i, 0, visualizerSettings.fftSize, -1, 1), 'hann', 1, true, 0);
fftData[i] = magnitude * w;
norm += w;
}
const spectrumData = calcComplexFFT(fftData.map(x => x*fftData.length/norm/Math.SQRT2));
const fgColor = visualizerSettings.darkMode ? '#fff' : '#000',
bgColor = visualizerSettings.darkMode ? '#000' : '#fff';
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = fgColor;
ctx.strokeStyle = fgColor;
// log-freq spectrum
const spectrum = spectrumData.map(x => x.magnitude),
halfSpectrum = spectrum.slice(0, visualizerSettings.useWrongWay ? spectrum.length : Math.round(spectrum.length/2)+1); // necessary for spectral features
if (visualizerSettings.showSpectrum) {
ctx.beginPath();
for (let i = 0; i < spectrum.length; i++) {
const x = spectrum[i];
// log frequency scale
ctx.lineTo(map(Math.log2(fftBinToHertz(i, visualizerSettings.fftSize, audioCtx.sampleRate)), Math.log2(20), Math.log2(20000), 0, canvas.width), map(20*Math.log10(x), -100, 0, canvas.height, 0));
}
ctx.stroke();
}
const textualData = [];
ctx.font = `${Math.trunc(10*devicePixelRatio)}px sans-serif`;
ctx.setLineDash([]);
if (visualizerSettings.showCentroid) {
const spectralCentroid = fftBinToHertz(mu(halfSpectrum), visualizerSettings.fftSize, audioCtx.sampleRate);
textualData.push({
label: `Spectral centroid`,
value: spectralCentroid >= 1000 ? `${spectralCentroid / 1000}kHz` : `${spectralCentroid}Hz`
});
drawLineAndLabel(spectralCentroid);
}
if (visualizerSettings.showSpread) {
const spectralSpread = fftBinToHertz(spread(halfSpectrum), visualizerSettings.fftSize, audioCtx.sampleRate);
textualData.push({
label: `Spectral spread`,
value: spectralSpread >= 1000 ? `${spectralSpread / 1000}kHz` : `${spectralSpread}Hz`
});
ctx.setLineDash([4,2]);
drawLineAndLabel(spectralSpread);
}
if (visualizerSettings.showRolloff) {
const spectralRolloff = fftBinToHertz(rolloff(halfSpectrum, visualizerSettings.rolloffThreshold), visualizerSettings.fftSize, audioCtx.sampleRate);
textualData.push({
label: `Spectral rolloff 1`,
value: spectralRolloff >= 1000 ? `${spectralRolloff / 1000}kHz` : `${spectralRolloff}Hz`
});
ctx.setLineDash([2,1]);
drawLineAndLabel(spectralRolloff);
}
if (visualizerSettings.showRolloff2) {
const spectralRolloff = fftBinToHertz(rolloff(halfSpectrum, visualizerSettings.rolloffThreshold2), visualizerSettings.fftSize, audioCtx.sampleRate);
textualData.push({
label: `Spectral rolloff 2`,
value: spectralRolloff >= 1000 ? `${spectralRolloff / 1000}kHz` : `${spectralRolloff}Hz`
});
ctx.setLineDash([2,1]);
drawLineAndLabel(spectralRolloff);
}
if (visualizerSettings.showRolloff3) {
const spectralRolloff = fftBinToHertz(rolloff(halfSpectrum, visualizerSettings.rolloffThreshold3), visualizerSettings.fftSize, audioCtx.sampleRate);
textualData.push({
label: `Spectral rolloff 3`,
value: spectralRolloff >= 1000 ? `${spectralRolloff / 1000}kHz` : `${spectralRolloff}Hz`
});
ctx.setLineDash([2,1]);
drawLineAndLabel(spectralRolloff);
}
if (visualizerSettings.showFlatness) {
const spectralFlatness = flatness(halfSpectrum);
textualData.push({
label: `Spectral flatness`,
value: `${spectralFlatness}`
});
}
if (visualizerSettings.showKurtosis) {
const spectralKurtosis = kurtosis(halfSpectrum);
textualData.push({
label: `Spectral kurtosis`,
value: `${spectralKurtosis}`
});
}
if (visualizerSettings.showSkewness) {
const spectralSkewness = skewness(halfSpectrum);
textualData.push({
label: `Spectral skewness`,
value: `${spectralSkewness}`
});
}
if (visualizerSettings.showSlope) {
const slope = spectralSlope(halfSpectrum, visualizerSettings.fftSize, audioCtx.sampleRate);
textualData.push({
label: `Spectral slope`,
value: `${slope}`
});
}
ctx.setLineDash([]);
if (visualizerSettings.showCrest) {
const crest = spectralCrest(halfSpectrum),
y = map(20*Math.log10(crest), 0, 100, canvas.height, 0);
textualData.push({
label: `Spectral crest`,
value: `${20*Math.log10(crest)}dB (${crest})`
});
ctx.globalAlpha = 0.5;
ctx.beginPath();
ctx.lineTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
ctx.globalAlpha = 1;
ctx.fillText(`${20*Math.log10(crest)}dB`, 0, y);
}
for (let i = 0; i < textualData.length; i++) {
ctx.fillText(`${textualData[i].label}: ${textualData[i].value}`, 10*devicePixelRatio, (1+i*1.05)*(10*devicePixelRatio)+10*devicePixelRatio);
}
requestAnimationFrame(visualize);
}
// and here's the additional functions that we can need for this visualization
function applyWindow(posX, windowType = 'Hann', windowParameter = 1, truncate = true, windowSkew = 0) {
let x = windowSkew > 0 ? ((posX/2-0.5)/(1-(posX/2-0.5)*10*(windowSkew ** 2)))/(1/(1+10*(windowSkew ** 2)))*2+1 :
((posX/2+0.5)/(1+(posX/2+0.5)*10*(windowSkew ** 2)))/(1/(1+10*(windowSkew ** 2)))*2-1;
if (truncate && Math.abs(x) > 1)
return 0;
switch (windowType.toLowerCase()) {
default:
return 1;
case 'hanning':
case 'cosine squared':
case 'hann':
return Math.cos(x*Math.PI/2) ** 2;
case 'raised cosine':
case 'hamming':
return 0.54 + 0.46 * Math.cos(x*Math.PI);
case 'power of sine':
return Math.cos(x*Math.PI/2) ** windowParameter;
case 'circle':
case 'power of circle':
return Math.sqrt(1 - (x ** 2)) ** windowParameter;
case 'tapered cosine':
case 'tukey':
return Math.abs(x) <= 1-windowParameter ? 1 :
(x > 0 ?
(-Math.sin((x-1)*Math.PI/windowParameter/2)) ** 2 :
Math.sin((x+1)*Math.PI/windowParameter/2) ** 2);
case 'blackman':
return 0.42 + 0.5 * Math.cos(x*Math.PI) + 0.08 * Math.cos(x*Math.PI*2);
case 'nuttall':
return 0.355768 + 0.487396 * Math.cos(x*Math.PI) + 0.144232 * Math.cos(2*x*Math.PI) + 0.012604 * Math.cos(3*x*Math.PI);
case 'flat top':
case 'flattop':
return 0.21557895 + 0.41663158 * Math.cos(x*Math.PI) + 0.277263158 * Math.cos(2*x*Math.PI) + 0.083578947 * Math.cos(3*x*Math.PI) + 0.006947368 * Math.cos(4*x*Math.PI);
case 'kaiser':
return Math.cosh(Math.sqrt(1-(x ** 2))*(windowParameter ** 2))/Math.cosh(windowParameter ** 2);
case 'gauss':
case 'gaussian':
return Math.exp(-(windowParameter ** 2)*(x ** 2));
case 'cosh':
case 'hyperbolic cosine':
return Math.E ** (-(windowParameter ** 2)*(Math.cosh(x)-1));
case 'bartlett':
case 'triangle':
case 'triangular':
return 1 - Math.abs(x);
case 'poisson':
case 'exponential':
return Math.exp(-Math.abs(x * (windowParameter ** 2)));
case 'hyperbolic secant':
case 'sech':
return 1/Math.cosh(x * (windowParameter ** 2));
case 'quadratic spline':
return Math.abs(x) <= 0.5 ? -((x*Math.sqrt(2)) ** 2)+1 : (Math.abs(x*Math.sqrt(2))-Math.sqrt(2)) ** 2;
case 'parzen':
return Math.abs(x) > 0.5 ? -2 * ((-1 + Math.abs(x)) ** 3) : 1 - 24 * (Math.abs(x/2) ** 2) + 48 * (Math.abs(x/2) ** 3);
case 'welch':
return 1 - (x ** 2);
case 'ogg':
case 'vorbis':
return Math.sin(Math.PI/2 * Math.cos(x*Math.PI/2) ** 2);
case 'cascaded sine':
case 'cascaded cosine':
case 'cascaded sin':
case 'cascaded cos':
return 1 - Math.sin(Math.PI/2 * Math.sin(x*Math.PI/2) ** 2);
}
}
function mu(x, n = 1) {
let numerator = 0,
denominator = 0;
for (let i = 0; i < x.length; i++) {
numerator += (i ** n) * Math.abs(x[i]);
denominator += x[i];
}
return numerator / denominator
}
function spread(x) {
return Math.sqrt(mu(x, 2) - (mu(x) ** 2));
}
function rolloff(x, n = 90) {
let ec = 0;
for (let i = 0; i < x.length; i++) {
ec += x[i];
}
const threshold = n * ec / 100;
let binIdx = x.length-1;
for (let i = 0; i < x.length; i++) {
if (ec <= threshold)
break;
ec -= x[x.length-i-1];
binIdx = x.length-i-1;
}
return binIdx;
}
function flatness(x) {
let numerator = 0,
denominator = 0;
for (let i = 0; i < x.length; i++) {
numerator += Math.log(x[i]);
denominator += x[i];
}
return (Math.exp(numerator/x.length) * x.length) / denominator;
}
function kurtosis(x) {
const mu1 = mu(x),
mu2 = mu(x, 2),
mu3 = mu(x, 3),
mu4 = mu(x, 4);
return (-3 * (mu1 ** 4) + 6 * mu1 * mu2 - 4 * mu1 * mu3 + mu4)/((Math.sqrt(mu2 - (mu1 ** 2))) ** 4);
}
function skewness(x) {
const mu1 = mu(x),
mu2 = mu(x, 2),
mu3 = mu(x, 3);
return (2 * mu1 ** 3 - 3 * mu1 * mu2 + mu3)/((Math.sqrt(mu2 - (mu1 ** 2))) ** 3);
}
function spectralSlope(x, bufferSize = 4096, sampleRate = 44100) {
let xSum = 0,
ySum = 0,
powSum = 0,
ampSum = 0;
for (let i = 0; i < x.length; i++) {
const freq = i / bufferSize * sampleRate;
ySum += x[i];
powSum += freq ** 2;
xSum += freq;
ampSum += freq * x[i];
}
return (x.length * ampSum - xSum * ySum)/(ySum * (powSum - (xSum ** 2)));
}
function spectralCrest(x) {
return Math.max(...x) / (Math.hypot(...x)/Math.sqrt(x.length));
}
function drawLineAndLabel(freq, displayText = true) {
const x = map(Math.log2(freq), Math.log2(20), Math.log2(20000), 0, canvas.width);
ctx.globalAlpha = 0.5;
ctx.beginPath();
ctx.lineTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
ctx.globalAlpha = 1;
if (displayText)
ctx.fillText(freq >= 1000 ? `${freq / 1000}kHz` : `${freq}Hz`, x, canvas.height);
}
/*navigator.mediaDevices.getUserMedia({
audio: {
noiseCancellation: false,
echoCancellation: false,
autoGainControl: false
},
video: false
}).then((stream) => {
const audioStream = audioCtx.createMediaStreamSource(stream);
//audioStream.connect(splitter); // for use with multi-channel visualizations
audioStream.connect(analyser);
//audioStream.connect(audioProvider); // for use with AudioWorklet-based visualizations
}).catch((err) => {
console.log(err);
});*/
Also see: Tab Triggers