Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

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.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

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.

+ add another resource

Packages

Add Packages

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.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <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>
              
            
!

CSS

              
                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;
}
              
            
!

JS

              
                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();
const convolver = audioCtx.createConvolver();
analyser.fftSize = 32768; // maxes out FFT size
const dataArray = new Float32Array(analyser.fftSize);
let freqResponseArray = [],
    irResponseArray = [];
audioSource.connect(convolver);
convolver.connect(audioCtx.destination);
convolver.connect(analyser);
const wavToExport = new wavefile.WaveFile();

const visualizerSettings = {
  type: 'spectrum',
  fftSize: 4096,
  minFreq: 20,
  maxFreq: 20000,
  fscale: 'logarithmic',
  hzLinearFactor: 0,
  minDecibels: -90,
  maxDecibels: 0,
  freeze: false,
  showResponse: true,
  showLabels: true,
  showLabelsY: true,
  darkMode: false,
},
      eqSettings = {
        numBands: 24,
        minFreq: 20,
        maxFreq: 20000,
        fscale: 'bark',
        linearFactor: 0,
        irLength: 100,
        preamp: 0,
        irExportName: 'eq impulse',
        bitDepth: '32f',
        sampleRate: 48000,
        export: exportIR
      },
      visualizationType = [
        'spectrum',
        'waveform'
      ],
      fscaleSettings = [
        'bark',
        'erb',
        'mel',
        'linear',
        'logarithmic',
        'sinh',
        'shifted log',
        'nth root',
        'negative exponential'
      ],
      loader = {
        url: '',
        load: function() {
          audioPlayer.src = this.url;
          audioPlayer.play();
        },
        loadLocal: function() {
          localAudioElement.click();
        }
      };

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', visualizationType).name('Visualization type');
settings.add(visualizerSettings, 'minFreq', 0, 22050).name('Minimum frequency');
settings.add(visualizerSettings, 'maxFreq', 0, 22050).name('Maximum frequency');
settings.add(visualizerSettings, 'fscale', fscaleSettings).name('Frequency scale');
settings.add(visualizerSettings, 'hzLinearFactor', 0, 100).name('Hz linear factor');
settings.add(visualizerSettings, 'fftSize', 32, 32768, 1).name('FFT size');
settings.add(visualizerSettings, 'minDecibels', -120, 0).name('Lower amplitude range');
settings.add(visualizerSettings, 'maxDecibels', -120, 0).name('Higher amplitude range');
settings.add(visualizerSettings, 'freeze').name('Freeze analyser');
settings.add(visualizerSettings, 'showResponse').name('Show filter response');
settings.add(visualizerSettings, 'showLabels').name('Show horizontal-axis labels');
settings.add(visualizerSettings, 'showLabelsY').name('Show vertical-axis labels');
settings.add(visualizerSettings, 'darkMode').name('Dark mode');
let bandsFolder = gui.addFolder('Graphic equalizer');
let bands = [];
for (let i = 0; i < 32; i++) {
  bands[i] = {value: 0};
  bandsFolder.add(bands[i], 'value', -24, 24).name(`${i + 1} band`).onFinishChange(updateIR);
}
let eqSettingsFolder = gui.addFolder('Graphic EQ settings');
eqSettingsFolder.add(eqSettings, 'preamp', -24, 24).name('Preamp').onFinishChange(updateIR);
eqSettingsFolder.add(eqSettings, 'numBands', 2, bands.length, 1).name('Number of bands').onFinishChange(updateIR);
eqSettingsFolder.add(eqSettings, 'minFreq', 0, 22050).name('Minimum frequency range').onFinishChange(updateIR);
eqSettingsFolder.add(eqSettings, 'maxFreq', 0, 22050).name('Maximum frequency range').onFinishChange(updateIR);
eqSettingsFolder.add(eqSettings, 'fscale', fscaleSettings).name('Frequency scale').onFinishChange(updateIR);
eqSettingsFolder.add(eqSettings, 'linearFactor', 0, 1).name('Hz linear factor').onFinishChange(updateIR);
eqSettingsFolder.add(eqSettings, 'irLength', 20, 2000).name('Impulse response length').onFinishChange(updateIR);
const exportFolder = eqSettingsFolder.addFolder('Export as impulse response file');
exportFolder.add(eqSettings, 'sampleRate', 8000, 192000, 1).name('Sample rate');
exportFolder.add(eqSettings, 'bitDepth', {
  'Single-precision (float32)': '32f',
  'Double-precision (float64)': '64'
}).name('Bit depth');
exportFolder.add(eqSettings, 'irExportName').name('Impulse response file name');
exportFolder.add(eqSettings, 'export').name('Export as audio file');

function resizeCanvas() {
  const scale = devicePixelRatio;
  canvas.width = container.clientWidth*scale;
  canvas.height = 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
updateIR();
visualize();
function visualize() {
  if (!visualizerSettings.freeze) {
    analyser.getFloatTimeDomainData(dataArray);
  }
  const fftData = [];
  let norm = 0;
  for (let i = 0; i < visualizerSettings.fftSize; i++) {
    const x = map(i, 0, visualizerSettings.fftSize, -1, 1),
          w = applyWindow(x, visualizerSettings.type === 'spectrum' ? 'hann' : 'rectangular'),
          magnitude = dataArray[i+analyser.fftSize-visualizerSettings.fftSize];
    norm += w;
    fftData[i] = magnitude * w;
  }
  
  const spectrum = visualizerSettings.type === 'spectrum' ? calcFFT(fftData.map(x => x*(fftData.length/norm))) : fftData,
        bgColor = visualizerSettings.darkMode ? '#000' : '#fff',
        fgColor = visualizerSettings.darkMode ? '#fff' : '#000';
  ctx.fillStyle = bgColor;
  ctx.strokeStyle = bgColor;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = fgColor;
  ctx.strokeStyle = fgColor;
  // Waveform and spectrum (FFT) visualization part
  ctx.beginPath();
  if (visualizerSettings.type === 'spectrum')
    spectrum.map((x, i) => {
      ctx.lineTo(map(fscale(fftBinToHertz(i, fftData.length, audioCtx.sampleRate), visualizerSettings.fscale, visualizerSettings.hzLinearFactor/100), fscale(visualizerSettings.minFreq, visualizerSettings.fscale, visualizerSettings.hzLinearFactor/100), fscale(visualizerSettings.maxFreq, visualizerSettings.fscale, visualizerSettings.hzLinearFactor/100), 0, canvas.width),
                 map(20*Math.log10(x), visualizerSettings.minDecibels, visualizerSettings.maxDecibels, canvas.height, 0));
    });
  else
    spectrum.map((x, i, arr) => {
      ctx.lineTo(i*canvas.width/arr.length, map(x, -1, 1, canvas.height, 0));
    });
  ctx.stroke();
  // Impulse response and frequency response part
  if (visualizerSettings.showResponse) {
    ctx.beginPath();
    if (visualizerSettings.type === 'spectrum')
      freqResponseArray.map((x, i) => {
        ctx.lineTo(map(fscale(fftBinToHertz(i, irResponseArray.length, audioCtx.sampleRate), visualizerSettings.fscale, visualizerSettings.hzLinearFactor/100), fscale(visualizerSettings.minFreq, visualizerSettings.fscale, visualizerSettings.hzLinearFactor/100), fscale(visualizerSettings.maxFreq, visualizerSettings.fscale, visualizerSettings.hzLinearFactor/100), 0, canvas.width),
                   map(20*Math.log10(x*irResponseArray.length/Math.sqrt(2)), -24, 24, canvas.height, 0));
      });
    else
      irResponseArray.map((x, i, arr) => {
        ctx.lineTo(i*canvas.width/arr.length, map(x, -1, 1, canvas.height, 0));
      });
    ctx.stroke();
  }
  // label part
  ctx.font = `${Math.trunc(10*devicePixelRatio)}px sans-serif`;
  ctx.textAlign = 'start';
  // Time-frequency label part
  if (visualizerSettings.showLabels) {
    ctx.globalAlpha = 0.5;
    ctx.setLineDash([]);
    if (visualizerSettings.type === 'spectrum') 
      [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].map(x => {
        ctx.globalAlpha = 0.5;
        const label = (x >= 1000) ? `${x / 1000}kHz` : `${x}Hz`,
              posX = map(fscale(x, visualizerSettings.fscale, visualizerSettings.hzLinearFactor/100), fscale(visualizerSettings.minFreq, visualizerSettings.fscale, visualizerSettings.hzLinearFactor/100), fscale(visualizerSettings.maxFreq, visualizerSettings.fscale, visualizerSettings.hzLinearFactor/100), 0, canvas.width);
        ctx.beginPath();
        ctx.lineTo(posX, canvas.height);
        ctx.lineTo(posX, 0);
        ctx.stroke();
        ctx.globalAlpha = 1;
        ctx.fillText(label, posX, canvas.height);
      });
    else {
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(x =>{
        ctx.globalAlpha = 0.5;
        const label = `${Math.round(map(x, 0, 10, spectrum.length, 1))} samples`,
              posX = map(x, 0, 10, 0, canvas.width);
        ctx.beginPath();
        ctx.lineTo(posX, canvas.height);
        ctx.lineTo(posX, 0);
        ctx.stroke();
        ctx.globalAlpha = 1;
        ctx.fillText(label, posX, canvas.height);
      });
      if (visualizerSettings.showResponse)
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(x =>{
          ctx.globalAlpha = 0.5;
          const label = `${Math.round(map(x, 0, 10, irResponseArray.length, 1))} samples`,
                posX = map(x, 0, 10, 0, canvas.width);
          ctx.setLineDash([2, 4]);
          ctx.beginPath();
          ctx.lineTo(posX, canvas.height);
          ctx.lineTo(posX, 0);
          ctx.stroke();
          ctx.globalAlpha = 1;
          ctx.textAlign = 'end'
          ctx.fillText(label, posX, canvas.height);
        });
    }
    ctx.setLineDash([]);
    ctx.globalAlpha = 1;
    ctx.textAlign = 'start';
  }
  // Amplitude/decibel label part
  if (visualizerSettings.showLabelsY) {
    ctx.globalAlpha = 0.5;
    ctx.setLineDash([]);
    if (visualizerSettings.type === 'spectrum') {
      [0, -6, -12, -18, -24, -30, -36, -42, -48, -54, -60, -66, -72, -78, -84, -90].map(x => {
        ctx.globalAlpha = 0.5;
        const label = `${x}dB`,
              posY = map(x, visualizerSettings.minDecibels, visualizerSettings.maxDecibels, canvas.height, 0);
        ctx.beginPath();
        ctx.lineTo(0, posY);
        ctx.lineTo(canvas.width, posY);
        ctx.stroke();
        ctx.globalAlpha = 1;
        ctx.fillText(label, 0, posY);
      });
      if (visualizerSettings.showResponse)
        [24, 18, 12, 6, 0, -6, -12, -18, -24].map(x => {
          ctx.globalAlpha = 0.5;
          const label = `${x}dB`,
                posY = map(x, -24, 24, canvas.height, 0);
          ctx.setLineDash([2, 4]);
          ctx.beginPath();
          ctx.lineTo(0, posY);
          ctx.lineTo(canvas.width, posY);
          ctx.stroke();
          ctx.globalAlpha = 1;
          ctx.textAlign = 'end';
          ctx.fillText(label, canvas.width, posY);
        });
    }
    else
      [0, -6, -12, -18, -24, -Infinity].map(x => {
        ctx.globalAlpha = 0.5;
        const label = `${x}${isFinite(x) ? '' : ' '}dB`,
              posY = map(10 ** (x/20), -1, 1, canvas.height, 0);
        ctx.beginPath();
        ctx.lineTo(0, posY);
        ctx.lineTo(canvas.width, posY);
        ctx.stroke();
        // inverted part since waveform has negative polarity, since decibels is 20 * log10(abs(x))
        if (isFinite(x)) {
          ctx.beginPath();
          ctx.lineTo(0, canvas.height-posY);
          ctx.lineTo(canvas.width, canvas.height-posY);
          ctx.stroke();
        }
        ctx.globalAlpha = 1;
        ctx.fillText(label, 0, posY);
        if (isFinite(x))
          ctx.fillText(label, 0, canvas.height-posY);
      });
    ctx.setLineDash([]);
    ctx.globalAlpha = 1;
    ctx.textAlign = 'start'
  }
  requestAnimationFrame(visualize);
}

// additional functions
function updateIR() {
  const bufferSize = Math.round(eqSettings.irLength*audioCtx.sampleRate/1000/2) * 2,
        impulseResponse = audioCtx.createBuffer(1, bufferSize+1, audioCtx.sampleRate);
  freqResponseArray = [];
  irResponseArray = [];
  convolver.buffer = null;
  let impulseResponseData = calcEQResponse(eqSettings.numBands, bands.map(x => 10 ** ((x.value+eqSettings.preamp)/20)), eqSettings.minFreq, eqSettings.maxFreq, eqSettings.fscale, eqSettings.linearFactor, bufferSize, audioCtx.sampleRate);
  transform(impulseResponseData, impulseResponseData.map(x => 0));
  const firData = impulseResponse.getChannelData(0);
  for (let i = 0; i < firData.length; i++) {
    firData[i] = impulseResponseData[idxWrapOver(i, bufferSize)]/firData.length * 2 * applyWindow(map(i, 0, firData.length-1, -1, 1), 'hann');
    irResponseArray[i] = firData[i];
  }
  freqResponseArray = calcFFT(irResponseArray);
  convolver.normalize = false;
  convolver.buffer = impulseResponse;
}

function exportIR() {
  const sampleRate = eqSettings.sampleRate,
        bufferSize = Math.round(eqSettings.irLength*sampleRate/1000/2) * 2,
        impulseResponse = [],
        impulseResponseData = calcEQResponse(eqSettings.numBands, bands.map(x => 10 ** ((x.value+eqSettings.preamp)/20)), eqSettings.minFreq, eqSettings.maxFreq, eqSettings.fscale, eqSettings.linearFactor, bufferSize, sampleRate);
  transform(impulseResponseData, impulseResponseData.map(x => 0));
  for (let i = 0; i <= bufferSize; i++) {
    impulseResponse[i] = impulseResponseData[idxWrapOver(i, bufferSize)]/(bufferSize+1) * 2 * applyWindow(map(i, 0, bufferSize, -1, 1), 'hann');
  }
  wavToExport.fromScratch(1, eqSettings.sampleRate, eqSettings.bitDepth, impulseResponse);
  exportToAudioFile(wavToExport.toBuffer(), eqSettings.irExportName);
}

function calcEQResponse(N = 24, gains = [], minFreq = 20, maxFreq = 20000, scale = 'bark', linearFactor = 0.5, bufferSize = 4410, sampleRate = 44100) {
  let data = new Array(bufferSize).fill(0);
  for (let band = 0; band < N; band++) {
    const lowerBound = map(band-1, 0, N-1, fscale(minFreq, scale, linearFactor), fscale(maxFreq, scale, linearFactor)),
          higherBound = map(band+1, 0, N-1, fscale(minFreq, scale, linearFactor), fscale(maxFreq, scale, linearFactor)),
          type = band > 0 && band < N-1 ? 'bandpass' : (band > 0 ? 'highpass' : 'lowpass'),
          minIdx = type === 'bandpass' || type === 'highpass' ? (clamp(hertzToFFTBin(invFscale(lowerBound, scale, linearFactor), 'floor', bufferSize, sampleRate), 0, bufferSize/2)) : 0,
          maxIdx = type === 'bandpass' || type === 'lowpass' ? (clamp(hertzToFFTBin(invFscale(higherBound, scale, linearFactor), 'ceil', bufferSize, sampleRate), 0, bufferSize/2)) : bufferSize/2,
          magnitude = (gains[band] === undefined) ? 1 : gains[band];
    for (let i = minIdx; i <= maxIdx; i++) {
      let posX = i/bufferSize*sampleRate;
      posX = map(fscale(posX, scale, linearFactor), lowerBound, higherBound, -1, 1);
      const polarity = -(-1+2*(i%2)),
            isWithinBounds = Math.abs(i) <= 0 || Math.abs(i) >= bufferSize/2;
      data[i] += ((Math.abs(posX) <= 1 && ((Math.sign(posX) * (-1+(type === 'highpass')*2)) <= 0 || type === 'bandpass') ? applyWindow(posX, 'hann') : Math.max(Math.sign(posX) * (-1+(type === 'highpass')*2), 0) * (type !== 'bandpass'))*polarity) * magnitude * (1-isWithinBounds/2);
    }
  }
  return data;
}

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 '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 '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);
  }
}

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 '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))));
  }
}

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 '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));
  }
}

function exportToAudioFile(data, fileName) {
  const a = document.createElement('a'),
        blob = new Blob([data], {type: 'audio/wav'}),
        tempURL = URL.createObjectURL(blob);
  a.setAttribute('href', tempURL);
  a.setAttribute('download', `${fileName}.wav`);
  a.click();
  URL.revokeObjectURL(tempURL);
}
              
            
!
999px

Console