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])
};
});
}
/**
* 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;
}
const audioCtx = new AudioContext();
const audioPlayer = document.getElementById('audio');
const localAudioElement = document.getElementById('audioFileInput');
localAudioElement.addEventListener('change', loadLocalFile);
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);
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 = {
type: 'fft',
numBands: 96,
fftSize: 4096,
minFreq: 20,
maxFreq: 20000,
minNote: 4,
maxNote: 124,
noteTuning: 440,
octaves: 12,
detune: 0,
bandwidth: 0.5,
bandwidthOffset: 1,
freqDist: 'octaves',
fscale: 'logarithmic',
windowFunction: 'hann',
windowParameter: 1,
windowSkew: 0,
timeAlignment: 1,
downsample: 0,
granularDownsample: false,
averageSamplesInstead: false,
interpSize: 32,
summationMode: 'max',
useComplex: true,
smoothInterp: true,
smoothSlope: true,
smoothingTimeConstant: 0,
smoothingMode: 'avg',
holdTime: 30,
fallRate: 0.5,
clampPeaks: true,
peakMode: 'gravity',
showPeaks: true,
hzLinearFactor: 0,
minDecibels: -90,
maxDecibels: 0,
useDecibels: true,
gamma: 1,
useAbsolute: true,
freeze: false,
color: 'none',
showLabels: true,
showLabelsY: true,
amplitudeLabelInterval: 6,
labelTuning: 440,
showDC: true,
showNyquist: true,
mirrorLabels: true,
diffLabels: false,
labelMode : 'decade',
barSpacing: 1,
spacingMode: 'smooth',
centerBars: false,
peakHeight: 1,
useLED: false,
ledStrips: 128,
darkMode: false,
compensateDelay: false
},
windowFunctionSettings = {
'Rectangular': 'rectangular',
'Triangular (Bartlett)': 'triangular',
'Quadratic': 'quadratic spline',
'Parzen': 'parzen',
'Welch': 'welch',
'Power of sine': 'power of sine',
'Power of circle': 'circle',
'Tukey (tapered cosine)': 'tukey',
'Vorbis': 'vorbis',
'Cascaded sine': 'cascaded sine',
'Hann': 'hann',
'Hamming': 'hamming',
'Blackman': 'blackman',
'Nuttall': 'nuttall',
'Flat top': 'flattop',
'Gaussian': 'gauss',
'Hyperbolic cosine': 'cosh',
'Kaiser': 'kaiser',
'Poisson': 'exponential',
'Hyperbolic secant': 'sech'
},
fscaleSettings = {
'Bark': 'bark',
'ERB': 'erb',
'Cams': 'cam',
'Mel (AIMP)': 'mel',
'Linear': 'linear',
'Logarithmic': 'logarithmic',
'Hyperbolic sine': 'sinh',
'Shifted logarithmic': 'shifted log',
'Nth root': 'nth root',
'Negative exponential': 'negative exponential',
'Adjustable Bark': 'adjustable bark',
'Period': 'period'
},
freqDistSettings = {
'Octave bands': 'octaves',
'Frequency bands': 'freqs',
'Avee Player': 'avee'
},
typeSettings = {
'FFT': 'fft',
'CQT': 'cqt',
'Filter bank energies': 'filterbank'
},
colorSettings = {
'None': 'none',
'Classic': 'classic',
'Rainbow': 'rainbow',
'Voice-Change-o-Matic': 'mdn',
'foobar2000': 'fb2k',
'foobar2000 (classic)': 'fb2k 2',
'Prism': 'prism 2',
'Prism (foo_musical_spectrum)': 'prism',
'Prism (classic)': 'prism 3',
'Audition': 'audition',
'WMP Bars': 'wmp',
'Ocean Mist': 'ocean',
'Fire Storm': 'firestorm'
},
averagingOptions = {
'Average': 'avg',
'Peak': 'peak'
},
bandpowerAttributes = {
'Maximum': 'max',
'Minimum': 'min',
'Average': 'avg',
'RMS': 'rms',
'Sum': 'sum',
'RMS sum': 'rms sum',
'Median': 'median'
},
labelModes = {
'Decades': 'decade',
'Octaves': 'octave',
'Notes': 'note',
'Automatic': 'auto'
},
peakModes = {
'Classic': 'classic',
'Gravity': 'gravity',
'AIMP': 'aimp'
},
loader = {
url: '',
load: function() {
audioPlayer.src = this.url;
audioPlayer.play();
},
loadLocal: function() {
localAudioElement.click();
},
toggleFullscreen: _ => {
if (document.fullscreenElement === canvas)
document.exitFullscreen();
else
canvas.requestFullscreen();
}
};
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');
settings.add(visualizerSettings, 'type', typeSettings).name('Visualization algorithm');
settings.add(visualizerSettings, 'freqDist', freqDistSettings).name('Frequency band distribution');
// up to 192kHz sample rate is supported for full-range visualization
settings.add(visualizerSettings, 'minFreq', 0, 96000).name('Minimum frequency');
settings.add(visualizerSettings, 'maxFreq', 0, 96000).name('Maximum frequency');
settings.add(visualizerSettings, 'minNote', 0, 128).name('Minimum note');
settings.add(visualizerSettings, 'maxNote', 0, 128).name('Maximum note');
settings.add(visualizerSettings, 'noteTuning', 0, 96000).name('Octave bands tuning (nearest note = tuning frequency in Hz)');
settings.add(visualizerSettings, 'detune', -24, 24).name('Detune');
settings.add(visualizerSettings, 'fscale', fscaleSettings).name('Frequency scale');
settings.add(visualizerSettings, 'hzLinearFactor', 0, 100).name('Hz linear factor');
settings.add(visualizerSettings, 'numBands', 2, 1920, 1).name('Number of bands');
settings.add(visualizerSettings, 'octaves', 1, 192).name('Bands per octave');
settings.add(visualizerSettings, 'bandwidth', 0, 64).name('Bandwidth');
settings.add(visualizerSettings, 'bandwidthOffset', 0, 1).name('Transition smoothness');
settings.add(visualizerSettings, 'fftSize', 32, 32768, 1).name('Max time resolution (samples)');
settings.add(visualizerSettings, 'timeAlignment', -1, 1).name('CQT kernel time alignment');
settings.add(visualizerSettings, 'downsample', 0, 100).name('Downsample amount');
settings.add(visualizerSettings, 'granularDownsample').name('Unlock downsampling amount from power of two');
settings.add(visualizerSettings, 'averageSamplesInstead').name('Average samples instead of skipping for downsampled part of CQT');
settings.add(visualizerSettings, 'interpSize', 1, 64, 1).name('Lanczos interpolation kernel size');
settings.add(visualizerSettings, 'smoothInterp').name('Smoother bin interpolation on lower frequencies');
settings.add(visualizerSettings, 'useComplex').name('Use complex FFT coefficients as interpolation data');
settings.add(visualizerSettings, 'summationMode', bandpowerAttributes).name('Bandpower summation mode');
settings.add(visualizerSettings, 'smoothSlope').name('Smoother frequency slope on sum modes');
settings.add(visualizerSettings, 'windowFunction', windowFunctionSettings).name('Window function');
settings.add(visualizerSettings, 'windowParameter', 0, 10).name('Window parameter');
settings.add(visualizerSettings, 'windowSkew', -1, 1).name('Window skew');
settings.add(visualizerSettings, 'smoothingTimeConstant', 0, 100).name('Smoothing time constant');
settings.add(visualizerSettings, 'smoothingMode', averagingOptions).name('Time smoothing method');
settings.add(visualizerSettings, 'holdTime', 0, 120).name('Peak hold time');
settings.add(visualizerSettings, 'fallRate', 0, 2).name('Peak fall rate');
settings.add(visualizerSettings, 'peakMode', peakModes).name('Peak decay behavior');
settings.add(visualizerSettings, 'clampPeaks').name('Clamp peaks');
settings.add(visualizerSettings, 'useDecibels').name('Use logarithmic amplitude/decibel scale');
settings.add(visualizerSettings, 'useAbsolute').name('Use absolute value');
settings.add(visualizerSettings, 'gamma', 0.5, 10).name('Gamma');
settings.add(visualizerSettings, 'minDecibels', -120, 6).name('Lower amplitude range');
settings.add(visualizerSettings, 'maxDecibels', -120, 6).name('Higher amplitude range');
settings.add(visualizerSettings, 'freeze').name('Freeze analyser');
settings.add(visualizerSettings, 'showPeaks').name('Show peaks');
settings.add(visualizerSettings, 'peakHeight', 0.5, 32).name('Peak indicator height');
settings.add(visualizerSettings, 'color', colorSettings).name('Visualization color');
settings.add(visualizerSettings, 'showLabels').name('Show horizontal-axis labels');
settings.add(visualizerSettings, 'showLabelsY').name('Show vertical-axis labels');
settings.add(visualizerSettings, 'amplitudeLabelInterval', 0.5, 48).name('dB label interval');
settings.add(visualizerSettings, 'showDC').name('Show DC label');
settings.add(visualizerSettings, 'showNyquist').name('Show Nyquist frequency label');
settings.add(visualizerSettings, 'mirrorLabels').name('Mirror Y-axis labels');
settings.add(visualizerSettings, 'diffLabels').name('Use difference coloring for labels');
settings.add(visualizerSettings, 'labelMode', labelModes).name('Frequency label mode');
settings.add(visualizerSettings, 'labelTuning', 0, 96000).name('Note labels tuning (nearest note = tuning frequency in Hz)');
settings.add(visualizerSettings, 'barSpacing', 0, 1024).name('Bar spacing');
settings.add(visualizerSettings, 'spacingMode', ['rough', 'smooth', 'pixel perfect']).name('Bar spacing mode');
settings.add(visualizerSettings, 'centerBars').name('Center bars');
settings.add(visualizerSettings, 'useLED').name('Use LEDs');
settings.add(visualizerSettings, 'ledStrips', 2, 1080, 1).name('LED strip count');
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);
}
const test = map(0, 0, 1, -1, 1); // Smoke testing
visualize();
function visualize() {
delay.delayTime.value = visualizerSettings.compensateDelay ? map(visualizerSettings.type === 'cqt' ? visualizerSettings.timeAlignment : -1, -1, 1, visualizerSettings.fftSize/audioCtx.sampleRate, 0) : 0;
if (!visualizerSettings.freeze) {
analyser.getFloatTimeDomainData(dataArray);
}
const fftData = new Array(visualizerSettings.fftSize),
isNumerical = visualizerSettings.freqDist === 'avee',
hzLinearFactor = visualizerSettings.hzLinearFactor/100,
bandwidth = visualizerSettings.type === 'cqt' || visualizerSettings.type === 'filterbank' ? visualizerSettings.bandwidth : 0.5;
let norm = 0;
for (let i = 0; i < visualizerSettings.fftSize; i++) {
const magnitude = dataArray[i+analyser.fftSize-visualizerSettings.fftSize],
w = visualizerSettings.type === 'cqt' ? 2 : applyWindow(map(i, 0, visualizerSettings.fftSize, -1, 1), visualizerSettings.windowFunction, visualizerSettings.windowParameter, true, visualizerSettings.windowSkew);
fftData[i] = magnitude * w;
norm += w;
}
let freqBands = [];
switch (visualizerSettings.freqDist) {
case 'octaves':
freqBands = generateOctaveBands(visualizerSettings.octaves, visualizerSettings.minNote, visualizerSettings.maxNote, visualizerSettings.detune, visualizerSettings.noteTuning, bandwidth);
break;
case 'avee':
freqBands = generateAveePlayerFreqs(visualizerSettings.numBands, visualizerSettings.minFreq, visualizerSettings.maxFreq, hzLinearFactor, bandwidth);
break;
default:
freqBands = generateFreqBands(visualizerSettings.numBands, visualizerSettings.minFreq, visualizerSettings.maxFreq, visualizerSettings.fscale, hzLinearFactor, bandwidth);
}
let spectrum;
if (visualizerSettings.type === 'cqt')
spectrum = cqt(fftData, freqBands, audioCtx.sampleRate, visualizerSettings.bandwidthOffset, visualizerSettings.timeAlignment, (x) => applyWindow(x, visualizerSettings.windowFunction, visualizerSettings.windowParameter, true, visualizerSettings.windowSkew), visualizerSettings.downsample/100, visualizerSettings.granularDownsample, visualizerSettings.averageSamplesInstead);
else {
const complexSpectrum = calcComplexFFT(fftData.map(x => x*fftData.length/norm/Math.SQRT2)),
fullSpectrum = complexSpectrum.map(x => x.magnitude),
useComplex = visualizerSettings.useComplex;
if (visualizerSettings.type === 'filterbank')
spectrum = calcFilterBankEnergies(freqBands, fullSpectrum, fftData.length, audioCtx.sampleRate);
else
spectrum = calcSpectrum(useComplex ? complexSpectrum : fullSpectrum, freqBands, visualizerSettings.interpSize, visualizerSettings.summationMode, useComplex, visualizerSettings.smoothInterp, visualizerSettings.smoothSlope, fftData.length, audioCtx.sampleRate);
}
const minLabelRange = Math.min(...freqBands.map(x => x.ctr)),
maxLabelRange = Math.max(...freqBands.map(x => x.ctr)),
bgColor = visualizerSettings.darkMode ? (visualizerSettings.color === 'fb2k' ? '#202020' : '#000') : '#fff',
fgColor = visualizerSettings.darkMode ? (visualizerSettings.color === 'fb2k' ? '#c0c0c0' : '#fff') : '#000',
ledStripHeight = Math.min(canvas.height / visualizerSettings.ledStrips, visualizerSettings.peakHeight);
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = bgColor;
ctx.strokeStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
let grad,
peakColor = fgColor;
switch (visualizerSettings.color) {
case 'prism':
case 'prism 2':
case 'prism 3':
case 'classic':
case 'fb2k 2':
case 'fb2k':
grad = ctx.createLinearGradient(0, 0, 0, canvas.height);
if (visualizerSettings.color === 'prism') {
grad.addColorStop(0/5, '#fd0000');
grad.addColorStop(1/5, '#ff8000');
grad.addColorStop(2/5, '#ffff01');
grad.addColorStop(3/5, '#7eff77');
grad.addColorStop(4/5, '#0193a2');
grad.addColorStop(5/5, '#002161');
peakColor = grad;
}
else if (visualizerSettings.color === 'prism 2') {
grad.addColorStop(0, '#a35');
grad.addColorStop(1/9, '#c66');
grad.addColorStop(2/9, '#e94');
grad.addColorStop(3/9, '#ed0');
grad.addColorStop(4/9, '#9d5');
grad.addColorStop(5/9, '#4d8');
grad.addColorStop(6/9, '#2cb');
grad.addColorStop(7/9, '#0bc');
grad.addColorStop(8/9, '#09c');
grad.addColorStop(1, '#36b');
peakColor = grad;
}
else if (visualizerSettings.color === 'prism 3') {
grad.addColorStop(0, 'hsl(0, 100%, 50%)');
grad.addColorStop(1/4, 'hsl(60, 100%, 50%)');
grad.addColorStop(2/4, 'hsl(120, 100%, 50%)');
grad.addColorStop(3/4, 'hsl(180, 100%, 50%)');
grad.addColorStop(1, 'hsl(240, 100%, 50%)');
}
else if (visualizerSettings.color === 'classic') {
grad.addColorStop(0, '#f00');
grad.addColorStop(0.5, '#ff0');
grad.addColorStop(1, '#0f0');
}
else if (visualizerSettings.color === 'fb2k 2') {
grad.addColorStop(0, visualizerSettings.darkMode ? 'rgb(0, 128, 255)' : '#008');
grad.addColorStop(1, visualizerSettings.darkMode ? '#fff' : '#000');
}
else {
grad.addColorStop(0, visualizerSettings.darkMode ? '#569cd6' : 'rgb(0, 102, 204)');
grad.addColorStop(1, visualizerSettings.darkMode ? '#c0c0c0' : '#000');
}
ctx.fillStyle = grad;
break;
case 'audition':
peakColor = '#fafa1a';
const highColor = '#f64646',
midColor = '#f5d145',
lowColor = '#36ed45',
mindBColor = 10 ** (-30/20),
maxdBColor = 10 ** (-12/20),
startPoint = isNaN(ascale(mindBColor)) ? 0 : clamp(ascale(mindBColor), 0, 1),
endPoint = isNaN(ascale(maxdBColor)) ? 0 : clamp(ascale(maxdBColor), 0, 1);
grad = ctx.createLinearGradient(0, canvas.height, 0, 0);
grad.addColorStop(0, lowColor);
grad.addColorStop(startPoint, lowColor);
grad.addColorStop(startPoint, midColor);
grad.addColorStop(endPoint, midColor);
grad.addColorStop(endPoint, highColor);
ctx.fillStyle = grad;
break;
default:
if (visualizerSettings.color === 'wmp') {
grad = '#a7ed03';
peakColor = '#e7f0ef';
}
else if (visualizerSettings.color === 'ocean') {
grad = '#00f';
peakColor = '#fff';
}
else if (visualizerSettings.color === 'firestorm') {
grad = '#fea500';
peakColor = '#f00';
}
ctx.fillStyle = fgColor;
}
ctx.strokeStyle = fgColor;
currentSpectrum.length = spectrum.length;
/*peaks.length = currentSpectrum.length;
peakHolds.length = peaks.length;
peakAccels.length = peaks.length;*/
switch(visualizerSettings.smoothingMode) {
case 'avg':
calcSmoothingTimeConstant(currentSpectrum, spectrum, visualizerSettings.smoothingTimeConstant/100);
break;
case 'peak':
calcPeakDecay(currentSpectrum, spectrum, visualizerSettings.smoothingTimeConstant/100);
break;
default:
currentSpectrum = spectrum.map(x => Math.max(x));
}
calcDecay(currentSpectrum.map(ascale), peaks, peakHolds, peakAccels)
currentSpectrum.map((x, i, arr) => {
const frequencyInNotes = Math.log2(freqBands[i].ctr/visualizerSettings.labelTuning);
switch(visualizerSettings.color) {
case 'mdn':
ctx.fillStyle = `rgb(${isNaN(ascale(x)) ? 0 : map(Math.max(Math.min(ascale(x), 1), 0), 0, 1, 0, 255)}, 50, 50)`;
break;
case 'rainbow':
const color = `hsl(${isFinite(frequencyInNotes) ? frequencyInNotes * 360 : 0}, 100%, ${isFinite(frequencyInNotes) ? (50) : (visualizerSettings.darkMode * 100)}%)`;
ctx.fillStyle = color;
ctx.strokeStyle = color;
}
/*
if (ascale(x) >= peaks[i] || isNaN(peaks[i]) || peaks[i] <= 0) {
peaks[i] = ascale(x);
peakHolds[i] = visualizerSettings.holdTime;
peakAccels[i] = 0;
}
else if (peakHolds[i] > 0)
peakHolds[i] -= 1;
else {
peakAccels[i] += visualizerSettings.fallRate / 256;
peaks[i] -= peakAccels[i];
}*/
const pos = Math[visualizerSettings.spacingMode === 'smooth' ? 'max' : 'trunc'](i * canvas.width / arr.length) + Math.min(visualizerSettings.barSpacing, canvas.width / arr.length)/2 * visualizerSettings.centerBars,
width = Math.max(1, (visualizerSettings.spacingMode === 'pixel perfect' ? Math.trunc((i+1) * canvas.width / arr.length)-Math.trunc(i * canvas.width / arr.length) : Math[visualizerSettings.spacingMode === 'smooth' ? 'max' : 'trunc'](canvas.width / arr.length))-visualizerSettings.barSpacing);
ctx.fillStyle = grad !== undefined ? grad : ctx.fillStyle;
if (visualizerSettings.useLED)
ctx.fillRect(pos, canvas.height, width, map(Math.round(Math.max(ascale(x), 0)*visualizerSettings.ledStrips), 0, visualizerSettings.ledStrips, 0, -canvas.height));
else
ctx.fillRect(pos, canvas.height, width, map(Math.max(ascale(x), 0), 0, 1, 0, -canvas.height));
ctx.fillStyle = peakColor;
if (visualizerSettings.showPeaks) {
if (visualizerSettings.useLED)
ctx.fillRect(pos, Math.round(map(peaks[i], 0, 1, visualizerSettings.ledStrips, 0))*canvas.height/visualizerSettings.ledStrips, width, canvas.height/visualizerSettings.ledStrips);
else
ctx.fillRect(pos, map(peaks[i], 0, 1, canvas.height, 0), width, visualizerSettings.peakHeight);
}
});
ctx.fillStyle = bgColor;
if (visualizerSettings.useLED) {
for (let i = 0; i < visualizerSettings.ledStrips; i++) {
const size = canvas.height / visualizerSettings.ledStrips;
ctx.fillRect(0, i * size, canvas.width, ledStripHeight);
}
}
ctx.globalCompositeOperation = visualizerSettings.diffLabels ? 'difference' : 'source-over';
ctx.fillStyle = visualizerSettings.diffLabels ? '#fff' : fgColor;
ctx.strokeStyle = visualizerSettings.diffLabels ? '#fff' : fgColor;
// label part
ctx.font = `${Math.trunc(10*devicePixelRatio)}px sans-serif`;
ctx.textAlign = 'start';
// Frequency label part
if (visualizerSettings.showLabels || visualizerSettings.showDC || visualizerSettings.showNyquist) {
const labelScale = visualizerSettings.freqDist === 'octaves' ? 'log' : visualizerSettings.fscale;
ctx.globalAlpha = 0.5;
ctx.setLineDash([]);
const freqLabels = [],
isNote = visualizerSettings.labelMode === 'note',
notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
let freqsTable;
switch(visualizerSettings.labelMode) {
case 'decade':
freqsTable = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000];
break;
case 'octave':
freqsTable = [31, 63.5, 125, 250, 500, 1000, 2000, 4000, 8000, 16000];
break;
case 'note':
freqsTable = generateOctaveBands(12, 0, 132, 0, visualizerSettings.labelTuning).map(x => x.ctr);
break;
default:
freqsTable = freqBands.map(x => x.ctr);
}
if (visualizerSettings.showLabels)
freqLabels.push(...freqsTable);
if (visualizerSettings.showDC)
freqLabels.push(0);
if (visualizerSettings.showNyquist)
freqLabels.push(audioCtx.sampleRate/2);
freqLabels.map(x => {
const note = isFinite(Math.log2(x)) ? notes[idxWrapOver(Math.round(Math.log2(x)*12), notes.length)] : 'DC',
isSharp = note.includes('#'),
isC = note === 'C';
ctx.globalAlpha = isNote ? (isSharp ? 0.2 : isC ? 0.8 : 0.5) : 0.5;
const label = x === audioCtx.sampleRate/2 && visualizerSettings.showNyquist ? 'Nyquist' : isNote || x === 0 ? `${note}${isC ? Math.trunc(Math.log2(x)-4) : ''}` : (x >= 1000) ? `${x / 1000}kHz` : `${x}Hz`,
posX = isNumerical ? getLabelPosFromFreqBands(freqBands, x)*canvas.width/freqBands.length : map(fscale(x, labelScale, visualizerSettings.hzLinearFactor/100), fscale(minLabelRange, labelScale, visualizerSettings.hzLinearFactor/100), fscale(maxLabelRange, labelScale, visualizerSettings.hzLinearFactor/100), canvas.width/spectrum.length/2, canvas.width - canvas.width/spectrum.length/2);
ctx.beginPath();
ctx.lineTo(posX, canvas.height);
ctx.lineTo(posX, 0);
ctx.stroke();
ctx.globalAlpha = 1;
ctx.fillText(label, posX, canvas.height);
});
ctx.setLineDash([]);
ctx.globalAlpha = 1;
ctx.textAlign = 'start';
}
// Amplitude/decibel label part
if (visualizerSettings.showLabelsY) {
const dBLabelData = [-Infinity],
mindB = Math.min(visualizerSettings.minDecibels, visualizerSettings.maxDecibels),
maxdB = Math.max(visualizerSettings.minDecibels, visualizerSettings.maxDecibels),
minLabelIdx = Math.round(mindB/visualizerSettings.amplitudeLabelInterval),
maxLabelIdx = Math.round(maxdB/visualizerSettings.amplitudeLabelInterval);
if (isFinite(minLabelIdx) && isFinite(maxLabelIdx)) {
for (let i = maxLabelIdx; i >= minLabelIdx; i--) {
dBLabelData.push(i*visualizerSettings.amplitudeLabelInterval);
}
}
ctx.globalAlpha = 0.5;
ctx.setLineDash([]);
dBLabelData.map(x => {
ctx.globalAlpha = 0.5;
const label = `${x}dB`,
posY = map(ascale(10 ** (x/20)), 0, 1, canvas.height, 0);
ctx.beginPath();
ctx.lineTo(0, posY);
ctx.lineTo(canvas.width, posY);
ctx.stroke();
ctx.globalAlpha = 1;
ctx.textAlign = visualizerSettings.mirrorLabels ? 'end' : 'start'
ctx.fillText(label, canvas.width * visualizerSettings.mirrorLabels, posY);
});
ctx.setLineDash([]);
ctx.globalAlpha = 1;
ctx.textAlign = 'start'
}
requestAnimationFrame(visualize);
}
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 fscale(x, freqScale = 'logarithmic', freqSkew = 0.5) {
switch(freqScale.toLowerCase()) {
default:
return x;
case 'log':
case 'logarithmic':
return Math.log2(x);
case 'mel':
return Math.log2(1+x/700);
case 'critical bands':
case 'bark':
return (26.81*x)/(1960+x)-0.53;
case 'equivalent rectangular bandwidth':
case 'erb':
return Math.log2(1+0.00437*x);
case 'cam':
case 'cams':
return Math.log2((x/1000+0.312)/(x/1000+14.675));
case 'sinh':
case 'arcsinh':
case 'asinh':
return Math.asinh(x/(10 ** (freqSkew*4)));
case 'shifted log':
case 'shifted logarithmic':
return Math.log2((10 ** (freqSkew*4))+x);
case 'nth root':
return x ** (1/(11-freqSkew*10));
case 'negative exponential':
return -(2 ** (-x/(2 ** (7+freqSkew*8))));
case 'adjustable bark':
return (26.81 * x)/((10 ** (freqSkew*4)) + x);
case 'period':
return 1/x;
}
}
function invFscale(x, freqScale = 'logarithmic', freqSkew = 0.5) {
switch(freqScale.toLowerCase()) {
default:
return x;
case 'log':
case 'logarithmic':
return 2 ** x;
case 'mel':
return 700 * ((2 ** x) - 1);
case 'critical bands':
case 'bark':
return 1960 / (26.81/(x+0.53)-1);
case 'equivalent rectangular bandwidth':
case 'erb':
return (1/0.00437) * ((2 ** x) - 1);
case 'cam':
case 'cams':
return (14.675 * (2 ** x) - 0.312)/(1-(2 ** x)) * 1000;
case 'sinh':
case 'arcsinh':
case 'asinh':
return Math.sinh(x)*(10 ** (freqSkew*4));
case 'shifted log':
case 'shifted logarithmic':
return (2 ** x) - (10 ** (freqSkew*4));
case 'nth root':
return x ** ((11-freqSkew*10));
case 'negative exponential':
return -Math.log2(-x)*(2 ** (7+freqSkew*8));
case 'adjustable bark':
return (10 ** (freqSkew*4)) / (26.81 / x - 1);
case 'period':
return 1/x;
}
}
function ascale(x) {
if (visualizerSettings.useDecibels)
return map(20*Math.log10(x), visualizerSettings.minDecibels, visualizerSettings.maxDecibels, 0, 1);
else
return map(x ** (1/visualizerSettings.gamma), !visualizerSettings.useAbsolute * (10 ** (visualizerSettings.minDecibels/20)) ** (1/visualizerSettings.gamma), (10 ** (visualizerSettings.maxDecibels/20)) ** (1/visualizerSettings.gamma), 0, 1);
}
/**
* Constant-Q Transform (CQT) calculated using Goertzel algorithm
*
* This by itself doesn't need Web Audio API in order to work but it is necessary for real-time visualizations
*
* Real-time usage:
* analyserNode.getFloatTimeDomainData(dataArray);
* const spectrum = cqt(dataArray, freqBands, audioCtx.sampleRate, bandwidthOffset, windowFunction);
*
* Note: the implementation of this CQT is slow compared to FFT
*/
function cqt(waveform, hzArray = generateOctaveBands(), sampleRate = 44100, bandwidthOffset = 1, alignment = 1, windowFunction = applyWindow, downsample = 0, granularDownsample = false, averageSamplesInstead = false) {
return hzArray.map(x => {
const bandwidth = Math.abs(x.hi - x.lo) + (sampleRate/waveform.length) * bandwidthOffset,
tlen = Math.min(1/bandwidth, waveform.length/sampleRate),
granularDownsampleAmount = Math.max(1, Math.trunc((sampleRate*downsample) / (x.ctr + tlen))),
downsampleAmount = granularDownsample ? granularDownsampleAmount : 2 ** Math.trunc(Math.log2(granularDownsampleAmount));
const coeff = 2 * Math.cos(2*Math.PI*x.ctr/sampleRate*downsampleAmount);
let f1 = 0,
f2 = 0,
sine,
offset = Math.trunc((waveform.length-tlen*sampleRate)*(0.5+alignment/2)),
lowerIdx = offset,
higherIdx = Math.trunc(tlen*sampleRate)+offset-1,
norm = 0;
for (let i = Math.trunc(lowerIdx/downsampleAmount); i <= Math.trunc(higherIdx/downsampleAmount); i++) {
let data = 0;
if (averageSamplesInstead && isFinite(downsampleAmount)) {
for (let j = 0; j < downsampleAmount; j++) {
data += (i*downsampleAmount+j) < waveform.length ? waveform[i*downsampleAmount+j] : 0;
}
data /= downsampleAmount;
}
else {
data = waveform[i*downsampleAmount];
}
let posX = (i*downsampleAmount - lowerIdx) / (higherIdx - lowerIdx) * 2 - 1;
let w = windowFunction(posX);
norm += w;
// Goertzel transform
sine = data*w + coeff * f1 - f2;
f2 = f1;
f1 = sine;
}
return Math.sqrt(f1 ** 2 + f2 ** 2 - coeff * f1 * f2) / norm;
});
}
function generateFreqBands(N = 128, low = 20, high = 20000, freqScale, freqSkew, bandwidth = 0.5) {
let freqArray = [];
for (let i = 0; i < N; i++) {
freqArray.push({
lo: invFscale( map(i-bandwidth, 0, N-1, fscale(low, freqScale, freqSkew), fscale(high, freqScale, freqSkew)), freqScale, freqSkew),
ctr: invFscale( map(i, 0, N-1, fscale(low, freqScale, freqSkew), fscale(high, freqScale, freqSkew)), freqScale, freqSkew),
hi: invFscale( map(i+bandwidth, 0, N-1, fscale(low, freqScale, freqSkew), fscale(high, freqScale, freqSkew)), freqScale, freqSkew)
});
}
return freqArray;
}
function generateOctaveBands(bandsPerOctave = 12, lowerNote = 4, higherNote = 123, detune = 0, tuningFreq = 440, bandwidth = 0.5) {
const tuningNote = isFinite(Math.log2(tuningFreq)) ? Math.round((Math.log2(tuningFreq)-4)*12)*2 : 0,
root24 = 2 ** ( 1 / 24 ),
c0 = tuningFreq * root24 ** -tuningNote, // ~16.35 Hz
groupNotes = 24/bandsPerOctave;
let bands = [];
for (let i = Math.round(lowerNote*2/groupNotes); i <= Math.round(higherNote*2/groupNotes); i++) {
bands.push({
lo: c0 * root24 ** ((i-bandwidth)*groupNotes+detune),
ctr: c0 * root24 ** (i*groupNotes+detune),
hi: c0 * root24 ** ((i+bandwidth)*groupNotes+detune)
});
}
return bands;
}
// Calculate band frequencies, method derived from Avee Player
function generateAveePlayerFreqs(N, minFreq = 20, maxFreq = 20000, hzLinearFactor = 0, bandwidth = 0.5) {
const freqBands = [];
for (let i = 0; i < N; i++) {
freqBands[i] = {
lo: logSpace(minFreq, maxFreq, i-bandwidth, N-1, hzLinearFactor),
ctr: logSpace(minFreq, maxFreq, i, N-1, hzLinearFactor),
hi: logSpace(minFreq, maxFreq, i+bandwidth, N-1, hzLinearFactor),
lowerBound: logSpace(minFreq, maxFreq, i-0.5, N-1, hzLinearFactor),
higherBound: logSpace(minFreq, maxFreq, i+0.5, N-1, hzLinearFactor)
};
}
return freqBands;
}
function logSpace(x, y, z, w, l) {
const centerFreq = x * ((y/x) ** (z/w));
return centerFreq * (1-l) + (x + ((y - x) * z * (1/w))) * l;
}
// needed for positioning Hz labels and ticks correctly where frequency band values are derived numerically rather than from closed-form frequency scale equations
function getLabelPosFromFreqBands(freqBands, x) {
let idx = 0;
if (x <= freqBands[0].lowerBound || x >= freqBands[freqBands.length-1].higherBound) {
idx = (freqBands.length-1) * (x >= freqBands[freqBands.length-1].higherBound);
}
else {
for (let i = 0; i < freqBands.length; i++) {
if ((x >= freqBands[i].lowerBound && x <= freqBands[i].higherBound)) {
idx = i;
break;
}
}
}
return map(x, freqBands[idx].lowerBound, freqBands[idx].higherBound, idx, idx+1);
}
// Calculates bandpower from FFT (foobar2000 flavored, can be enhanced by using complex FFT coefficients instead of magnitude-only FFT data)
function calcSpectrum(fftCoeffs, freqBands, interpSize = 4, summationMode = 'max', useComplex = false, smoothInterp = true, smoothGainTransition = true, bufferSize = 4410, sampleRate = 44100) {
return freqBands.map(x => {
const minIdx = hertzToFFTBin(Math.min(x.hi, x.lo), 'ceil', bufferSize, sampleRate),
maxIdx = hertzToFFTBin(Math.max(x.hi, x.lo), 'floor', bufferSize, sampleRate),
minIdx2 = smoothInterp ? hertzToFFTBin(Math.min(x.hi, x.lo), 'round', bufferSize, sampleRate) + 1 : minIdx,
maxIdx2 = smoothInterp ? hertzToFFTBin(Math.max(x.hi, x.lo), 'round', bufferSize, sampleRate) - 1 : maxIdx,
bandGain = smoothGainTransition && (summationMode === 'sum' || summationMode === 'rms sum') ? Math.hypot(1, ((x.hi - x.lo) * bufferSize / sampleRate) ** (1-(summationMode === 'rms' || summationMode === 'rms sum')/2)) : 1;
if (minIdx2 > maxIdx2)
return Math.abs(lanzcos(fftCoeffs, x.ctr * bufferSize / sampleRate, interpSize, useComplex)) * bandGain;
else {
let sum = summationMode === 'min' ? Infinity : 0,
diff = 0;
const overflowCompensation = Math.max(maxIdx - minIdx - bufferSize, 0),
isAverage = (summationMode === 'avg' || summationMode === 'rms') || ((summationMode === 'sum' || summationMode === 'rms sum') && smoothGainTransition),
isRMS = summationMode === 'rms' || summationMode === 'rms sum',
isMedian = summationMode === 'median',
medianData = [];
for (let i = minIdx; i <= maxIdx - overflowCompensation; i++) {
const binIdx = (i % fftCoeffs.length + fftCoeffs.length) % fftCoeffs.length,
data = useComplex ? fftCoeffs[binIdx].magnitude : fftCoeffs[binIdx];
switch(summationMode) {
case 'max':
sum = Math.max(data, sum)
break;
case 'min':
sum = Math.min(data, sum);
break;
case 'avg':
case 'rms':
case 'sum':
case 'rms sum':
sum += data ** (1 + isRMS);
break;
case 'median':
medianData.push(data);
break;
default:
sum = data;
}
diff++;
}
if (isMedian)
sum = median(medianData);
else
sum /= isAverage ? diff : 1;
return (isRMS ? Math.sqrt(sum) : sum) * bandGain;
}
});
}
// Calculates spectrum based on Mel (or actually arbitrary frequency) filter bank energies
function calcFilterBankEnergies(freqBands, fftData, bufferSize = 4096, sampleRate = 44100) {
return freqBands.map(x => {
let sum = 0,
minBin = Math.min(x.lo, x.hi) * bufferSize / sampleRate,
midBin = x.ctr * bufferSize / sampleRate,
maxBin = Math.max(x.lo, x.hi) * bufferSize / sampleRate,
overflowCompensation = Math.max(0, maxBin-minBin-bufferSize);
for (let i = Math.floor(midBin); i >= Math.floor(minBin+overflowCompensation); i--) {
sum += (fftData[idxWrapOver(i, fftData.length)] * Math.max(map(i, minBin, midBin, 0, 1), 0)) ** 2;
}
for (let i = Math.ceil(midBin); i <= Math.ceil(maxBin-overflowCompensation); i++) {
sum += (fftData[idxWrapOver(i, fftData.length)] * Math.max(map(i, maxBin, midBin, 0, 1), 0)) ** 2;
}
return Math.sqrt(sum);
});
}
function lanzcos(data, x, kernelSize = 4, inSpectrum = false) {
let sum = 0,
complexSum = {
re: 0,
im: 0
};
for (let i = -kernelSize + 1; i <= kernelSize; i++) {
const pos = Math.floor(x)+i,//i+x,
twiddle = x-pos,//-pos+Math.round(pos)+i,
w = Math.abs(twiddle) <= 0 ? 1 : Math.sin(twiddle*Math.PI)/(twiddle*Math.PI) * Math.sin(Math.PI*twiddle/kernelSize)/(Math.PI*twiddle/kernelSize),
idx = (pos % data.length + data.length) % data.length;
if (inSpectrum) {
complexSum.re += data[idx].re * w * (-1 + (i % 2 + 2) % 2 * 2);
complexSum.im += data[idx].im * w * (-1 + (i % 2 + 2) % 2 * 2);
}
else
sum += data[idx] * w;
}
if (inSpectrum)
return Math.hypot(complexSum.re, complexSum.im);
else
return sum;
}
function calcSmoothingTimeConstant(targetArr, sourceArr, factor = 0.5) {
for (let i = 0; i < targetArr.length; i++) {
targetArr[i] = (isNaN(targetArr[i]) ? 0 : targetArr[i])*(factor)+(isNaN(sourceArr[i]) ? 0 : sourceArr[i])*(1-factor);
}
}
function calcPeakDecay(targetArr, sourceArr, factor = 0.5) {
for (let i = 0; i < targetArr.length; i++) {
targetArr[i] = Math.max(isNaN(targetArr[i]) ? 0 : targetArr[i] * factor, isNaN(sourceArr[i]) ? 0 : sourceArr[i]);
}
}
function median(data) {
if (!data.length)
return NaN;
else if (data.length <= 1)
return data[0];
const sortedData = data.slice().sort((x, y) => x-y),
half = Math.trunc(data.length/2);
if (data.length % 2)
return sortedData[half];
return (sortedData[half-1] + sortedData[half]) / 2;
}
// Peak decay calculation
function calcDecay(source, p, h, a) {
p.length = source.length;
h.length = p.length;
a.length = p.length;
for (let i = 0; i < p.length; i++) {
p[i] = isFinite(p[i]) ? p[i] : 0;
if (source[i] >= p[i]) {
h[i] = visualizerSettings.peakMode === 'aimp' ? (isFinite(h[i]) ? h[i] : 0) + ((visualizerSettings.clampPeaks ? Math.max(Math.min(source[i], 1), 0) : source[i]) - p[i]) * visualizerSettings.holdTime : visualizerSettings.holdTime;
p[i] = source[i];
a[i] = 0;
}
else if (h[i] >= 0) {
if (visualizerSettings.peakMode === 'aimp')
p[i] += (h[i] - Math.max(h[i]-1, 0))/visualizerSettings.holdTime;
h[i] -= 1;
h[i] = Math.min(h[i], visualizerSettings.holdTime/(visualizerSettings.peakMode !== 'aimp'));
}
else {
switch (visualizerSettings.peakMode) {
case 'gravity':
a[i] += visualizerSettings.fallRate / 256;
break;
case 'aimp':
a[i] = visualizerSettings.fallRate / 256 * ((p[i] < 0.5)+1);
break;
default:
a[i] = visualizerSettings.fallRate / 256
}
p[i] -= a[i];
}
p[i] = visualizerSettings.clampPeaks ? Math.max(Math.min(p[i], 1), 0) : p[i];
}
}
Also see: Tab Triggers