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>
<script>
/**
 * Single file implementation of sliding windowed infinite Fourier transform (SWIFT)
 *
 * The frequency bands data is formatted like:
 * {lo: lowerBound,
 *  ctr: center,
 *  hi: higherBound}
 *
 * where lo and hi are used for calculating the necessary bandwidth for variable-Q transform spectrum visualizations and ctr for center frequency. This is generated using functions like generateFreqBands
 */
class SWIFT {
  constructor(freqBands, order = 4, timeRes = 600, bandwidth = 1, sampleRate = 44100) {
    // initialize the sDFT coefficients
    this.calcCoeffs(freqBands, order, timeRes, bandwidth, sampleRate);
    this.spectrumData = [];
  }
  
  calcCoeffs(freqBands, order = 4, timeRes = 600, bandwidth = 1, sampleRate = 44100) {
    // calcCoeffs() can be called anywhere else to re-initialize sliding DFT after changes in frequency band distributions and note that x and y are used instead of real and imaginary since vector rotation is the equivalent of the complex one
    this._coeffs = [];
    freqBands.map((x, i) => {
      // rX and rY are calculated in advance here since calculating sin and cos functions are pretty slow af
      this._coeffs[i] = {
        rX: Math.cos(x.ctr*Math.PI/sampleRate*2),
        rY: Math.sin(x.ctr*Math.PI/sampleRate*2),
        decay: Math.E ** (-Math.abs(x.hi-x.lo) * 4 * bandwidth / sampleRate - 1/(timeRes*sampleRate/2000)),
        coeffs: []
      };
      for (let j = 0; j < order; j++) {
        this._coeffs[i].coeffs[j] = {
          x: 0,
          y: 0
        };
      }
    });
  }
  
  analyze(dataArray) {
    const newSpectrumData = new Array(this._coeffs.length).fill(0);
    for (const x of dataArray) {
      for (let i = 0; i < this._coeffs.length; i++) {
        for (let j = 0; j < this._coeffs[i].coeffs.length; j++) {
          const input = j <= 0 ? {
            x: x,
            y: 0,
          } : this._coeffs[i].coeffs[j-1];
          this._coeffs[i].coeffs[j] = {
            x: (this._coeffs[i].coeffs[j].x * this._coeffs[i].rX - this._coeffs[i].coeffs[j].y * this._coeffs[i].rY) * this._coeffs[i].decay + input.x * (1-this._coeffs[i].decay),
            y: (this._coeffs[i].coeffs[j].x * this._coeffs[i].rY + this._coeffs[i].coeffs[j].y * this._coeffs[i].rX) * this._coeffs[i].decay + input.y * (1-this._coeffs[i].decay)
          };
        }
        newSpectrumData[i] = Math.max(newSpectrumData[i],
                                      this._coeffs[i].coeffs[this._coeffs[i].coeffs.length-1].x ** 2 +
                                      this._coeffs[i].coeffs[this._coeffs[i].coeffs.length-1].y ** 2);
      }
    }
    this.spectrumData = newSpectrumData.map((x) => Math.sqrt(x));
  }
}
</script>
              
            
!

CSS

              
                body {
  margin: 0;
  overflow: hidden;
}

canvas {
  display: block;
  width: 100%;
}

#container {
  height: 100vh;
}
              
            
!

JS

              
                // No need for AudioWorklets nor Web Audio API
const canvas = document.getElementById('canvas'),
      ctx = canvas.getContext('2d'),
      container = document.getElementById('container'),
      settings = {
        // Frequency bands part
        numBands: 96,
        minFreq: 20,
        maxFreq: 20000,
        // SWIFT part
        order: 4,
        tRes: 100,
        bandwidth: 2,
        resetsDFT: updateSWIFT,
        sampleRate: 44100, //typical sampling rate
        hopSize: 735,
        // Signal generator part
        toneFreq: 50,
        toneAmplitude: 1,
        noiseAmplitude: 1,
      };
let sDFT = new SWIFT(generateFreqBands(settings.numBands, settings.minFreq, settings.maxFreq), settings.order, settings.tRes, settings.bandwidth, settings.sampleRate),
    t = 0;
const gui = new dat.GUI();
gui.add(settings, 'hopSize', 1, 4096, 1).name('Hop size');
let signalSettingsFolder = gui.addFolder('Signal generator settings');
signalSettingsFolder.add(settings, 'toneFreq', 20, 20000).name('Tone frequency');
signalSettingsFolder.add(settings, 'toneAmplitude', 0, 4).name('Tone amplitude');
signalSettingsFolder.add(settings, 'noiseAmplitude', 0, 4).name('Noise amplitude');
let algorithmSettingsFolder = gui.addFolder('SWIFT settings');
algorithmSettingsFolder.add(settings, 'order', 1, 8, 1).name('SWIFT filter bank order').onChange(updateSWIFT);
algorithmSettingsFolder.add(settings, 'tRes', 0, 1000).name('Maximum time resolution').onChange(updateSWIFT);
algorithmSettingsFolder.add(settings, 'bandwidth', 0, 8).name('Bandwidth').onChange(updateSWIFT);
algorithmSettingsFolder.add(settings, 'resetsDFT').name('Flush SWIFT');
let freqBandsSettingsFolder = gui.addFolder('Filter bank settings');
freqBandsSettingsFolder.add(settings, 'numBands', 2, 256, 1).name('Number of bands').onChange(updateSWIFT);
freqBandsSettingsFolder.add(settings, 'minFreq', 0, 22050).name('Minimum frequency').onChange(updateSWIFT);
freqBandsSettingsFolder.add(settings, 'maxFreq', 0, 22050).name('Maximum frequency').onChange(updateSWIFT);

function updateSWIFT() {
  sDFT.calcCoeffs(generateFreqBands(settings.numBands, settings.minFreq, settings.maxFreq), settings.order, settings.tRes, settings.bandwidth, settings.sampleRate);
}

function resizeCanvas() {
  const scale = devicePixelRatio;
  canvas.width = container.clientWidth*scale;
  canvas.height = container.clientHeight*scale;
}

addEventListener('resize', resizeCanvas);
resizeCanvas();

function map(x, min, max, targetMin, targetMax) {
  return (x - min) / (max - min) * (targetMax - targetMin) + targetMin;
}

function generateFreqBands(N = 96, low = 20, high = 20000) {
  let freqArray = [];
  for (let i = 0; i < N; i++) {
    freqArray.push({
      lo: 2 ** map(i-0.5, 0, N-1, Math.log2(low), Math.log2(high)),
      ctr: 2 ** map(i, 0, N-1, Math.log2(low), Math.log2(high)),
      hi: 2 ** map(i+0.5, 0, N-1, Math.log2(low), Math.log2(high))
    });
  }
  return freqArray;
}

visualize();
function visualize() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  let input = [];
  for (let i = 0; i < settings.hopSize; i++) {
    input[i] = Math.sin(t/settings.sampleRate*settings.toneFreq*Math.PI*2)*settings.toneAmplitude + (0.5-Math.random())*settings.noiseAmplitude;
    t++;
  }
  sDFT.analyze(input);
  ctx.beginPath();
  sDFT.spectrumData.map((x, i, arr) => {
    ctx.lineTo(i * canvas.width / (arr.length-1), canvas.height-x*canvas.height)
  });
  ctx.stroke();
  requestAnimationFrame(visualize);
}
              
            
!
999px

Console