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 id="CustomDSPEffect" type="worklet">
// Similar to Downmix channels to mono DSP effect from foobar2000, but preserves LFE effects
class DownmixToMono extends AudioWorkletProcessor {
constructor() {
super();
}
process(inputs, outputs, parameters) {
const input = inputs[0],
output = outputs[0],
dataArray = [];
for (let i = 0; i < input[0].length; i++) {
let sum = 0;
for (let j = 0; j < input.length; j++) {
sum += input[j][i];
}
dataArray[i] = sum/input.length;
}
input.forEach((channel, x) => {
for (let i = 0; i < channel.length; i++) {
output[x][i] = dataArray[i];
}
});
return true;
}
}
registerProcessor('downmix-channels-to-mono', DownmixToMono);
class BassBoost extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [{
name: 'freq',
defaultValue: 50,
minValue: 0
},{
name: 'gain',
defaultValue: 12
}];
}
constructor() {
super();
this.smoothedValues0 = [];
this.smoothedValues1 = [];
this.smoothedValues2 = [];
this.smoothedValues3 = [];
this.ampTodB = x => {
return 20*Math.log10(x);
};
this.dBToAmp = x => {
return 10 ** (x/20);
}
}
process(inputs, outputs, parameters) {
const decayTime = Math.E ** (-parameters.freq[0]/sampleRate*8),
input = inputs[0],
output = outputs[0];
this.smoothedValues0.length = input.length;
this.smoothedValues1.length = input.length;
this.smoothedValues2.length = input.length;
this.smoothedValues3.length = input.length;
input.forEach((channel, x) => {
for (let i = 0; i < channel.length; i++) {
const sample = channel[i];
this.smoothedValues0[x] = isFinite(this.smoothedValues0[x]) ? sample * (1-decayTime) + this.smoothedValues0[x] * decayTime : sample;
this.smoothedValues1[x] = isFinite(this.smoothedValues1[x]) ? this.smoothedValues0[x] * (1-decayTime) + this.smoothedValues1[x] * decayTime : this.smoothedValues0[x];
this.smoothedValues2[x] = isFinite(this.smoothedValues2[x]) ? this.smoothedValues1[x] * (1-decayTime) + this.smoothedValues2[x] * decayTime : this.smoothedValues1[x];
this.smoothedValues3[x] = isFinite(this.smoothedValues3[x]) ? this.smoothedValues2[x] * (1-decayTime) + this.smoothedValues3[x] * decayTime : this.smoothedValues2[x];
output[x][i] = input[x][i] + this.smoothedValues3[x] * (this.dBToAmp(parameters.gain[0])-1);
}
});
return true;
}
}
registerProcessor('bass-boost', BassBoost);
class CustomDSPEffect extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [{
name: 'strength',
defaultValue: 1
},
{
name: 'decay',
defaultValue: 1
}];
}
constructor() {
super();
this.values = [],
this.vels = [];
}
process(inputs, outputs, parameters) {
const input = inputs[0],
output = outputs[0],
strength = parameters.strength[0]/100,
decay = parameters.decay[0]/100;
this.values.length = input.length;
this.vels.length = this.values.length;
input.forEach((channel, x) => {
for (let i = 0; i < channel.length; i++) {
//this.values[x] = isFinite(this.values[x]) ? this.values[x]+strength*Math.sign(channel[i]-this.values[x]) : channel[i];
this.vels[x] = isFinite(this.vels[x]) ? this.vels[x]+strength*Math.sign(channel[i]-this.values[x]) : 0;
this.values[x] = isFinite(this.values[x]) ? (this.values[x]+this.vels[x])*(1-decay) : channel[i];
output[x][i] = this.values[x];
}
});
return true;
}
}
registerProcessor('custom-dsp-effect', CustomDSPEffect);
// Technically, we can register multiple processors within a single script in the similar way to how a single foobar2000 DSP component like Utility DSP Array and Effects DSP adds more than one DSP effect
// Simple peak compressor using leaky integrator
class CompressorProcessor extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [{
name: 'threshold',
defaultValue: -12
},{
name: 'threshold2',
defaultValue: -48
},{
name: 'upperLimit',
defaultValue: 60
},{
name: 'lowerLimit',
defaultValue: 30
},{
name: 'ratio',
defaultValue: 2
},{
name: 'ratio2',
defaultValue: 1
},{
name: 'attack',
defaultValue: 5,
minValue: 0
},{
name: 'release',
defaultValue: 50,
minValue: 0
},{
name: 'makeupGain',
defaultValue: 0
},{
name: 'mix',
defaultValue: 100,
minValue: 0,
maxValue: 100
}];
}
constructor() {
super();
this.envelopeValues = [];
this.ampTodB = x => {
return 20*Math.log10(x);
};
this.dBToAmp = x => {
return 10 ** (x/20);
}
}
process(inputs, outputs, parameters) {
const input = inputs[0],
output = outputs[0],
attTime = Math.E ** (-1/(parameters.attack[0]*sampleRate/1000)),
relTime = Math.E ** (-1/(parameters.release[0]*sampleRate/1000)),
slope = 1 - (1/parameters.ratio[0]),
slope2 = 1 - (1/parameters.ratio2[0]);
this.envelopeValues.length = input.length;
input.forEach((channel, x) => {
for (let i = 0; i < channel.length; i++) {
const amp = this.ampTodB(Math.abs(channel[i]));
const gainReduction =
(Math.abs(slope) <= 0 ? 0 : Math.max(Math.min((-amp+parameters.threshold[0]), 0), -parameters.upperLimit[0]/Math.abs(slope)))*slope -
(Math.abs(slope2) <= 0 ? 0 : Math.min(Math.max((amp-parameters.threshold2[0]), -parameters.lowerLimit[0]/Math.abs(slope2)), 0))*slope2;
const smoothingTimeConstant = gainReduction > this.envelopeValues[x] ? relTime : attTime;
this.envelopeValues[x] = isFinite(this.envelopeValues[x]) ? gainReduction * (1-smoothingTimeConstant) + this.envelopeValues[x] * (smoothingTimeConstant) : gainReduction;
output[x][i] = input[x][i] * (this.dBToAmp(this.envelopeValues[x]) * parameters.mix[0]/100 + (1-parameters.mix[0]/100)) * this.dBToAmp(parameters.makeupGain[0]);
}
});
return true;
}
}
registerProcessor('compressor-processor', CompressorProcessor);
class LimiterProcessor extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [{
name: 'threshold',
defaultValue: 0
},{
name: 'attack',
defaultValue: 5,
minValue: 0
},{
name: 'release',
defaultValue: 50,
minValue: 0
},{
name: 'autoReleaseDiff',
defaultValue: 2,
minValue: 0,
},{
name: 'autoReleaseAmount',
defaultValue: 0,
},{
name: 'autoReleaseTime',
defaultValue: 100,
minValue: 0
}];
}
constructor() {
super();
this.envelopeValues = [];
this.fastEnvelopes = [];
this.slowEnvelopes = [];
this.ampTodB = x => {
return 20*Math.log10(x);
};
this.dBToAmp = x => {
return 10 ** (x/20);
}
}
process(inputs, outputs, parameters) {
const input = inputs[0],
output = outputs[0],
attTime = Math.E ** (-1/(parameters.attack[0]*sampleRate/1000)),
relTime = Math.E ** (-1/(parameters.release[0]*sampleRate/1000)),
// auto-release values
fastEnvTime = Math.E ** (-1/(parameters.autoReleaseTime[0]*sampleRate/1000)),
slowEnvTime = Math.E ** (-1/(parameters.autoReleaseTime[0]*parameters.autoReleaseDiff[0]*sampleRate/1000));
this.envelopeValues.length = input.length;
this.fastEnvelopes.length = input.length;
this.slowEnvelopes.length = input.length;
input.forEach((channel, x) => {
for (let i = 0; i < channel.length; i++) {
const linearAmp = Math.abs(input[x][i]);
this.fastEnvelopes[x] = isFinite(this.fastEnvelopes[x]) ? linearAmp * (1-fastEnvTime) + this.fastEnvelopes[x] * fastEnvTime : linearAmp;
this.slowEnvelopes[x] = isFinite(this.slowEnvelopes[x]) ? linearAmp * (1-slowEnvTime) + this.slowEnvelopes[x] * slowEnvTime : linearAmp;
const amp = this.ampTodB(Math.abs(channel[i])),
gainReduction = Math.min(0, -amp+parameters.threshold[0]),
envRatio = this.fastEnvelopes[x]/this.slowEnvelopes[x],
reductionSpeedMultiplier = parameters.autoReleaseAmount[0] !== 0 && isFinite(envRatio) ? envRatio ** (parameters.autoReleaseAmount[0]/100) : 1,
smoothingTimeConstant = (gainReduction > this.envelopeValues[x] ? relTime : attTime) ** reductionSpeedMultiplier;
this.envelopeValues[x] = isFinite(this.envelopeValues[x]) ? gainReduction * (1-smoothingTimeConstant) + this.envelopeValues[x] * (smoothingTimeConstant) : gainReduction;
output[x][i] = input[x][i] * this.dBToAmp(this.envelopeValues[x]-parameters.threshold[0]); // peaks can go above 0dBFS if attack time is more than zero because we don't apply a lookahead
}
});
return true;
}
}
registerProcessor('limiter-processor', LimiterProcessor);
class WinampEQLimiter extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [{
name: 'threshold',
defaultValue: 0
},{
name: 'ceiling',
defaultValue: 0
},{
name: 'release',
defaultValue: 700,
minValue: 0
},{
name: 'channelLink',
defaultValue: 100,
minValue: 0,
maxValue: 100
}];
}
constructor() {
super();
this.envelopeValues = [];
this.ampTodB = x => {
return 20*Math.log10(x);
};
this.dBToAmp = x => {
return 10 ** (x/20);
}
}
process(inputs, outputs, parameters) {
const input = inputs[0],
output = outputs[0],
relTime = 0.001 ** (1/(parameters.release[0]*sampleRate/1000));
this.envelopeValues.length = input.length;
const globalValue = [];
input.forEach((channel, x) => {
for (let i = 0; i < channel.length; i++) {
globalValue[i] = Math.max(isFinite(globalValue[i]) ? globalValue[i] : 0, Math.abs(channel[i])) * (parameters.channelLink[0] / 100);
}
});
input.forEach((channel, x) => {
for (let i = 0; i < channel.length; i++) {
const preamp = this.dBToAmp(-parameters.threshold[0]),
ceiling = this.dBToAmp(parameters.ceiling[0]),
amp = Math.max(Math.abs(input[x][i]), isFinite(globalValue[i]) ? globalValue[i] : 0) * preamp / ceiling;
this.envelopeValues[x] = Math.max(isFinite(this.envelopeValues[x]) ? this.envelopeValues[x] * relTime : isFinite(amp) ? amp : 0, isFinite(amp) ? amp : 0);
output[x][i] = input[x][i] * preamp * Math.min(1/this.envelopeValues[x], 1);
}
});
return true;
}
}
registerProcessor('waeqlim-dsp', WinampEQLimiter);
</script>
<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 delay = audioCtx.createDelay();
//audioSource.connect(delay);
//delay.connect(audioCtx.destination);
//audioSource.connect(audioCtx.destination);
//audioSource.connect(analyser);
let customDSPEffect;
const customDSPSource = document.getElementById('CustomDSPEffect'),
dspSourceBlob = new Blob([customDSPSource.innerText], {type: 'application/javascript'}),
dspSourceUrl = URL.createObjectURL(dspSourceBlob);
const visualizerSettings = {
fftSize: 1152,
type: 'waveform',
freeze: false
},
placeholderListData = {
'Option 1': 'one',
'Option 2': 'two'
},
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');
settings.add(visualizerSettings, 'type', {
'Waveform': 'waveform',
'Spectrum': 'spectrum'
}).name('Visualization type');
settings.add(visualizerSettings, 'freeze').name('Freeze analyzer');
// The additional parameters goes here
// another parameters at the end
//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();
audioCtx.audioWorklet.addModule(dspSourceUrl).then(() => {
//let messageCounter = 0;
// yeah, this below is an example of multiple different DSPs within a single module
//customDSPEffect = new AudioWorkletNode(audioCtx, 'limiter-processor');
customDSPEffect = new AudioWorkletNode(audioCtx, 'waeqlim-dsp');
const bassBoost = new AudioWorkletNode(audioCtx, 'bass-boost');
//downmixed = new AudioWorkletNode(audioCtx, 'downmix-channels-to-mono');
//audioSource.connect(downmixed);
//downmixed.connect(bassBoost);
audioSource.connect(bassBoost);
bassBoost.connect(customDSPEffect);
customDSPEffect.onprocessorerror = (e) => {
console.log(e.message);
}
customDSPEffect.connect(delay);
customDSPEffect.connect(analyser);
delay.connect(audioCtx.destination);
const dspFolder = gui.addFolder('AudioParams');
dspFolder.add(bassBoost.parameters.get('freq'), 'value', 0, 96000).name('Bass boost frequency');
dspFolder.add(bassBoost.parameters.get('gain'), 'value', -48, 48).name('Bass boost amount');
// Winamp EQ's limiter
dspFolder.add(customDSPEffect.parameters.get('threshold'), 'value', -60, 0).name('Threshold');
dspFolder.add(customDSPEffect.parameters.get('ceiling'), 'value', -60, 0).name('Ceiling');
dspFolder.add(customDSPEffect.parameters.get('release'), 'value', 0, 1000).name(`Release`);
dspFolder.add(customDSPEffect.parameters.get('channelLink'), 'value', 0, 100).name('Channel linking');
// my own peak limiter
/*
dspFolder.add(customDSPEffect.parameters.get('threshold'), 'value', -60, 0).name('Threshold');
dspFolder.add(customDSPEffect.parameters.get('attack'), 'value', 0, 1000).name(`Attack`);
dspFolder.add(customDSPEffect.parameters.get('release'), 'value', 0, 1000).name(`Release`);
dspFolder.add(customDSPEffect.parameters.get('autoReleaseDiff'), 'value', 0, 8).name('Auto-release envelope follower difference');
dspFolder.add(customDSPEffect.parameters.get('autoReleaseAmount'), 'value', -200, 200).name(`Auto-release amount`);
dspFolder.add(customDSPEffect.parameters.get('autoReleaseTime'), 'value', 0, 1000).name(`Auto-release envelope follower time`);
*/
/*
dspFolder.add(customDSPEffect.parameters.get('strength'), 'value', 0, 100).name('Strength');
dspFolder.add(customDSPEffect.parameters.get('decay'), 'value', 0, 100).name('Decay');
*/
/*
dspFolder.add(customDSPEffect.parameters.get('threshold'), 'value', -60, 0).name(`Upper threshold`);
dspFolder.add(customDSPEffect.parameters.get('ratio'), 'value', 0.1, 10).name(`Upper ratio`);
dspFolder.add(customDSPEffect.parameters.get('threshold2'), 'value', -60, 0).name(`Lower threshold`);
dspFolder.add(customDSPEffect.parameters.get('ratio2'), 'value', 0.1, 10).name(`Lower ratio`);
dspFolder.add(customDSPEffect.parameters.get('upperLimit'), 'value', 0, 60).name(`Upper limit`);
dspFolder.add(customDSPEffect.parameters.get('lowerLimit'), 'value', 0, 60).name(`Lower limit`);
dspFolder.add(customDSPEffect.parameters.get('attack'), 'value', 0, 1000).name(`Attack`);
dspFolder.add(customDSPEffect.parameters.get('release'), 'value', 0, 1000).name(`Release`);
dspFolder.add(customDSPEffect.parameters.get('makeupGain'), 'value', -48, 48).name(`Make-up gain`);
dspFolder.add(customDSPEffect.parameters.get('mix'), 'value', 0, 100).name(`Dry/wet mix`);
*/
visualize();
}).catch((e) => {
console.log(e.message);
});
function visualize() {
delay.delayTime.value = 0;
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 = [];
for (let i = 0; i < visualizerSettings.fftSize; i++) {
const x = map(i, 0, visualizerSettings.fftSize-1, -1, 1),
w = Math.cos(x*Math.PI/2) ** 2 * 2; // Hann window, to be consistent with ChannelGetData function from BASS audio library, especially the FFT part
fftData[i] = dataArray[i+analyser.fftSize-visualizerSettings.fftSize] * (visualizerSettings.type === 'spectrum' ? w : 1);
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (visualizerSettings.type === 'spectrum') {
const spectrumData = calcFFT(fftData),
minFreq = 20 * fftData.length / audioCtx.sampleRate,
maxFreq = 20000 * fftData.length / audioCtx.sampleRate;
ctx.beginPath();
for (let i = 0; i < spectrumData.length; i++) {
ctx.lineTo(map(Math.log2(i), Math.log2(minFreq), Math.log2(maxFreq), 0, canvas.width), map(Math.log10(spectrumData[i]), -4, 0, canvas.height, 0));
}
ctx.stroke();
}
else {
ctx.beginPath();
fftData.map((x, i, arr) => {
ctx.lineTo(map(i, 0, arr.length-1, 0.5, canvas.width-0.5), map(x, -1, 1, canvas.height, 0));
});
ctx.stroke();
}
requestAnimationFrame(visualize);
}
// and here's the additional functions that we can need for this visualization
Also see: Tab Triggers