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="AudioProvider" type="worklet">
class AudioProvider extends AudioWorkletProcessor {
constructor() {
super();
this.dataArrays = [];
this.bufferSize = 32768; // can handle more than 32768 samples of PCM data unlike in AnalyserNode.getFloatTimeDomainData, which is capped at 32768 samples
this.bufferIdx = 0;
this.currentTimeInSamples = 0;
this.port.onmessage = (e) => {
const audioChunks = [],
retrievalWindowSize = e.data ? Math.min(this.bufferSize, currentFrame - this.currentTimeInSamples) : this.bufferSize,
timeOffset = this.bufferSize-retrievalWindowSize;
for (let channelIdx = 0; channelIdx < this.dataArrays.length; channelIdx++) {
audioChunks[channelIdx] = [];
for (let i = 0; i < this.dataArrays[channelIdx].length-timeOffset; i++) {
const data = this.dataArrays[channelIdx][((this.bufferIdx+i+timeOffset) % this.bufferSize + this.bufferSize) % this.bufferSize];
audioChunks[channelIdx][i] = data !== undefined ? data : 0;
}
}
this.port.postMessage({currentChunk: audioChunks});
this.currentTimeInSamples = currentFrame;
};
}
process(inputs, _, _2) {
if (inputs[0].length <= 0)
return true;
this.dataArrays.length = inputs[0].length;
for (let i = 0; i < this.dataArrays.length; i++) {
if (this.dataArrays[i] === undefined)
this.dataArrays[i] = new Array(this.bufferSize);
else {
this.dataArrays[i].length = this.bufferSize;
}
}
for (let i = 0; i < inputs[0][0].length; i++) {
this.bufferIdx = Math.min(this.bufferIdx, this.bufferSize-1);
for (let channelIdx = 0; channelIdx < inputs[0].length; channelIdx++) {
this.dataArrays[channelIdx][this.bufferIdx] = inputs[0][channelIdx][i];
}
this.bufferIdx = ((this.bufferIdx + 1) % this.bufferSize + this.bufferSize) % this.bufferSize;
}
return true;
}
}
registerProcessor('audio-provider', AudioProvider);
</script>
<script>
class IIRFilter {
constructor(a0, a1, a2, b1, b2) {
this.recalcCoeffs(a0, a1, a2, b1, b2);
}
recalcCoeffs(a0 = 0, a1 = 0, a2 = 0, b1 = 0, b2 = 0) {
this.a0 = a0;
this.a1 = a1;
this.a2 = a2;
this.b1 = b1;
this.b2 = b2;
this.z1 = 0;
this.z2 = 0;
}
process(x) {
const output = x * this.a0 + this.z1;
this.z1 = x * this.a1 + this.z2 - this.b1 * output;
this.z2 = x * this.a2 - this.b2 * output;
return output;
}
}
class KWeighting {
constructor(sampleRate) {
this.highpass = new IIRFilter();
this.highshelf = new IIRFilter();
this.recalcCoeffs(sampleRate);
}
recalcCoeffs(sampleRate = 44100) {
const hpFreq = 80,
hpQ = Math.SQRT2/2,
hsFreq = 1500,
hsGain = 10 ** (4/20),
k1 = Math.tan(Math.PI * hpFreq/sampleRate),
k2 = Math.tan(Math.PI * hsFreq/sampleRate),
norm1 = 1 / (1 + k1 / hpQ + k1 ** 2),
norm2 = 1 / (1 + Math.SQRT2 * k2 + k2 ** 2);
// highpass part
const hpA0 = norm1,
hpA1 = -hpA0 * 2,
hpA2 = norm1,
hpB1 = 2 * (k1 ** 2 - 1) * norm1,
hpB2 = (1 - k1 / hpQ + k1 ** 2) * norm1,
// highshelf part
hsA0 = (hsGain + Math.sqrt(hsGain*2) * k2 + k2 ** 2) * norm2,
hsA1 = 2 * (k2 ** 2 - hsGain) * norm2,
hsA2 = (hsGain - Math.sqrt(hsGain*2) * k2 + k2 ** 2) * norm2,
hsB1 = 2 * (k2 ** 2 - 1) * norm2,
hsB2 = (1 - Math.SQRT2 * k2 + k2 ** 2) * norm2;
this.highpass.recalcCoeffs(
hpA0,
hpA1,
hpA2,
hpB1,
hpB2
);
this.highshelf.recalcCoeffs(
hsA0,
hsA1,
hsA2,
hsB1,
hsB2
);
}
process(x) {
return this.highshelf.process(this.highpass.process(x));
}
}
</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 oscilloscopeBuffer = [];
let oscilloscopeIdx = 0;
const delay = audioCtx.createDelay();
audioSource.connect(delay);
delay.connect(audioCtx.destination);
//audioSource.connect(audioCtx.destination);
audioSource.connect(analyser);
let audioProvider,
currentSampleRate = audioCtx.sampleRate;
const customDSPSource = document.getElementById('AudioProvider'),
dspSourceBlob = new Blob([customDSPSource.innerText], {type: 'application/javascript'}),
dspSourceUrl = URL.createObjectURL(dspSourceBlob);
const visualizerSettings = {
resetAverages: resetSmoothedValues,
// label part
showLabels: true,
showLabelsY: true,
amplitudeLabelInterval: 6,
minAmplitudeLabel: -24,
numDivisions: 10,
mirrorLabels: true,
diffLabels: false,
// triggering part
outputSize: 1920,
compensateDC: false,
polarity: 'up',
triggeringChannelMode: 'mono',
triggeringChannelIdx: 0,
reverseTriggeringIdx: false,
// other stuffs
freeze: false,
darkMode: false,
useGradient: true,
autoReset: true,
resetBoth: resetBoth,
fftSize: 3840,
compensateDelay: true
},
averagingDomains = {
'Linear': 'linear',
'Squared (RMS)': 'rms',
'Logarithmic': 'log'
},
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');
//const amplitudeFolder = settings.addFolder('Amplitude');
settings.add(visualizerSettings, 'fftSize', 32, 65536, 1).name('Input buffer length').onChange(resetBoth);
settings.add(visualizerSettings, 'outputSize', 32, 65536, 1).name('Output buffer length');
// triggering part
const triggerFolder = settings.addFolder('Oscilloscope triggering');
triggerFolder.add(visualizerSettings, 'compensateDC').name('Compensate for DC offset');
triggerFolder.add(visualizerSettings, 'polarity', {
'Up': 'up',
'Down': 'down',
'Both': 'both'}).name('Polarity');
triggerFolder.add(visualizerSettings, 'triggeringChannelMode', {
'Mono': 'mono',
'Single channel': 'single',
'Independent': 'independent'
}).name('Triggering channel mode');
triggerFolder.add(visualizerSettings, 'triggeringChannelIdx', 0, 32, 1).name('Triggering channel index');
triggerFolder.add(visualizerSettings, 'reverseTriggeringIdx').name('Reverse triggering channel index');
// label part
const labelFolder = settings.addFolder('Labels and grids');
labelFolder.add(visualizerSettings, 'showLabels').name('Show horizontal-axis labels');
labelFolder.add(visualizerSettings, 'showLabelsY').name('Show vertical-axis labels');
labelFolder.add(visualizerSettings, 'amplitudeLabelInterval', 0.5, 48).name('dB label interval');
labelFolder.add(visualizerSettings, 'minAmplitudeLabel', -90, 0).name('Minimum dB label display');
labelFolder.add(visualizerSettings, 'numDivisions', 2, 48, 1).name('Number of X-axis label divisions');
labelFolder.add(visualizerSettings, 'mirrorLabels').name('Mirror Y-axis labels');
labelFolder.add(visualizerSettings, 'diffLabels').name('Use difference coloring for labels');
settings.add(visualizerSettings, 'freeze').name('Freeze analyzer');
settings.add(visualizerSettings, 'darkMode').name('Dark mode');
settings.add(visualizerSettings, 'useGradient').name('Use brighter color on dark mode');
settings.add(visualizerSettings, 'autoReset').name('Enable auto-reset');
settings.add(visualizerSettings, 'compensateDelay').name('Compensate for delay');
settings.add(visualizerSettings, 'resetBoth').name('Reset oscilloscope');
gui.add(loader, 'toggleFullscreen').name('Toggle fullscreen mode');
function resetBoth() {
resetSmoothedValues();
}
function resetSmoothedValues() {
oscilloscopeBuffer.length = 0;
oscilloscopeIdx = 0;
}
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 autoReset() {
if (visualizerSettings.autoReset && !visualizerSettings.freeze)
resetBoth();
}
// this below makes it more faithful to how foobar2000 visualizations work
audioPlayer.addEventListener('play', autoReset);
audioPlayer.addEventListener('seeked', autoReset);
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;
audioProvider = new AudioWorkletNode(audioCtx, 'audio-provider');
audioSource.connect(audioProvider);
audioProvider.port.postMessage(0);
audioProvider.port.onmessage = (e) => {
if (!visualizerSettings.freeze)
analyzeChunk(e.data.currentChunk);
audioProvider.port.postMessage(1);
//if (messageCounter < 1) {
// console.log(e.data.currentChunk);
//}
//messageCounter++;
};
// optional mic input
/*navigator.mediaDevices.getUserMedia({
audio: {
noiseCancellation: false,
echoCancellation: false,
autoGainControl: false
},
video: false
}).then((stream) => {
const audioStream = audioCtx.createMediaStreamSource(stream);
audioStream.connect(analyser);
audioStream.connect(audioProvider); // for use with AudioWorklet-based visualizations
}).catch((err) => {
console.log(err);
});*/
audioProvider.onprocessorerror = (e) => {
console.log(e.message);
}
visualize();
}).catch((e) => {
console.log(e.message);
});
function analyzeChunk(data) {
const dataset = [];
let retrievalLength = 0;
for (const x of data) {
retrievalLength = Math.max(retrievalLength, x.length);
}
oscilloscopeBuffer.length = data.length;
for (let i = 0; i < data.length; i++) {
const length = visualizerSettings.fftSize;
if (oscilloscopeBuffer[i] === undefined)
oscilloscopeBuffer[i] = new Array(length);
else if (oscilloscopeBuffer[i].length !== length)
oscilloscopeBuffer[i].length = length;
}
for (let i = 0; i < retrievalLength; i++) {
for (let channelIdx = 0; channelIdx < data.length; channelIdx++) {
oscilloscopeBuffer[channelIdx][oscilloscopeIdx] = data[channelIdx][i];
}
oscilloscopeIdx = idxWrapOver(oscilloscopeIdx+1, visualizerSettings.fftSize);
}
currentSampleRate = audioCtx.sampleRate;
}
function visualize() {
const actualLength = Math.min(visualizerSettings.fftSize, visualizerSettings.outputSize);
delay.delayTime.value = (actualLength / audioCtx.sampleRate) * visualizerSettings.compensateDelay / 2;
/*if (!visualizerSettings.freeze) {
}*/
const fgColor = visualizerSettings.darkMode ? (visualizerSettings.useGradient ? '#c0c0c0' : '#fff') : '#000',
bgColor = visualizerSettings.darkMode ? (visualizerSettings.useGradient ? '#202020' : '#000') : '#fff';
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
let oscOffset = 0;
if (oscilloscopeBuffer.length > 0) {
if (visualizerSettings.triggeringChannelMode === 'single') {
const i = visualizerSettings.triggeringChannelIdx,
idx = idxWrapOver(visualizerSettings.reverseTriggeringIdx ? oscilloscopeBuffer.length-i-1 : i, oscilloscopeBuffer.length);
oscOffset = calcTriggeringOffset(renderOscilloscope(oscilloscopeBuffer, idx));
}
else if (visualizerSettings.triggeringChannelMode === 'mono')
oscOffset = calcTriggeringOffset(getMonoData(oscilloscopeBuffer));
}
ctx.fillStyle = fgColor;
ctx.strokeStyle = fgColor;
for (let i = 0; i < oscilloscopeBuffer.length; i++) {
const waveData = renderOscilloscope(oscilloscopeBuffer, i);
if (visualizerSettings.triggeringChannelMode === 'independent')
oscOffset = calcTriggeringOffset(waveData);
ctx.beginPath();
calcOscilloscope(waveData, oscOffset).map((x, idx, arr) => {
ctx.lineTo(idx*canvas.width/arr.length, (map(x, -1, 1, 1, 0)+i)*canvas.height/oscilloscopeBuffer.length);
});
ctx.stroke();
}
ctx.globalCompositeOperation = visualizerSettings.diffLabels ? 'difference' : 'source-over';
ctx.fillStyle = visualizerSettings.diffLabels ? '#fff' : fgColor;
ctx.strokeStyle = visualizerSettings.diffLabels ? '#fff' : fgColor;
// label part
const numChannels = oscilloscopeBuffer.length;
ctx.font = `${Math.trunc(10*devicePixelRatio)}px sans-serif`;
ctx.textAlign = 'start';
// time label part
if (visualizerSettings.showLabels) {
ctx.globalAlpha = 0.5;
ctx.setLineDash([]);
const labelData = [];
for (let i = 0; i <= visualizerSettings.numDivisions; i++) {
labelData[i] = i;
}
labelData.map(x =>{
ctx.globalAlpha = 0.5;
const label = `${Math.round(map(x, 0, visualizerSettings.numDivisions, actualLength, 0))} samples`,
posX = map(x, 0, visualizerSettings.numDivisions, 0, canvas.width);
ctx.beginPath();
ctx.lineTo(posX, canvas.height);
ctx.lineTo(posX, 0);
ctx.stroke();
ctx.globalAlpha = 1;
if (numChannels > 1) {
ctx.textBaseline = 'middle';
for (let i = 0; i < numChannels-1; i++) {
ctx.fillText(label, posX, (1+i)*canvas.height/numChannels);
}
}
else {
ctx.textBaseline = 'alphabetic';
ctx.fillText(label, posX, canvas.height);
}
});
ctx.setLineDash([]);
ctx.globalAlpha = 1;
ctx.textAlign = 'start'
ctx.textBaseline = 'alphabetic';
}
// amplitude/dB label part
if (visualizerSettings.showLabelsY) {
const dBLabelData = [-Infinity],
mindB = visualizerSettings.minAmplitudeLabel,
maxdB = 0,
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;
ctx.textBaseline = 'middle';
ctx.textAlign = visualizerSettings.mirrorLabels ? 'end' : 'start';
const label = `${x}${isFinite(x) ? '' : ' '}dB`,
posY = map(10 ** (x/20), -1, 1, canvas.height/numChannels, 0),
height = canvas.height/numChannels;
for (let i = 0; i < numChannels; i++) {
const offset = i*height,
y1 = posY+offset,
y2 = height-posY+offset;
ctx.globalAlpha = 0.5;
ctx.beginPath();
ctx.lineTo(0, y1);
ctx.lineTo(canvas.width, y1);
ctx.stroke();
// inverted part since waveform has negative polarity, since decibels is 20 * log10(abs(x))
if (isFinite(x)) {
ctx.beginPath();
ctx.lineTo(0, y2);
ctx.lineTo(canvas.width, y2);
ctx.stroke();
}
ctx.globalAlpha = 1;
ctx.fillText(label, canvas.width * visualizerSettings.mirrorLabels, y1);
if (isFinite(x))
ctx.fillText(label, canvas.width * visualizerSettings.mirrorLabels, y2);
}
});
ctx.setLineDash([]);
ctx.globalAlpha = 1;
ctx.textAlign = 'start';
ctx.textBaseline = 'alphabetic';
}
requestAnimationFrame(visualize);
}
// and here's the additional functions that we can need for this visualization
function renderOscilloscope(data, idx) {
const dataset = [];
for (let i = 0; i < data[idx].length; i++) {
dataset[i] = data[idx][idxWrapOver(i+oscilloscopeIdx-data[idx].length, data[idx].length)];
}
return dataset;
}
function getMonoData(data) {
const dataArray = [];
for (let i = 0; i < data.length; i++) {
renderOscilloscope(data, i).map((x, idx) => {
dataArray[idx] = (dataArray[idx] === undefined ? 0 : dataArray[idx]) + x/data.length;
});
}
return dataArray;
}
// zero-crossing based triggering
function calcTriggeringOffset(waveform, outputSize = visualizerSettings.outputSize, compensateDC = visualizerSettings.compensateDC, polarity = visualizerSettings.polarity) {
let dc = 0;
if (compensateDC) {
waveform.map(x => {
dc += isFinite(x) ? x : 0; // account for DC offset
});
dc /= waveform.length;
}
let idx = 0,
hasNotTriggered = true,
triggeringEnabled = false;
for (let i = 1; i < waveform.length-outputSize; i++) {
triggeringEnabled = true;
if (
((waveform[i-1] >= dc && waveform[i] < dc) && polarity !== 'up') ||
((waveform[i-1] < dc && waveform[i] >= dc) && polarity !== 'down')) {
idx = i;
hasNotTriggered = false;
}
}
return hasNotTriggered && triggeringEnabled ? waveform.length-outputSize-1 : idx;
}
function calcOscilloscope(data, offset = 0, outputSize = visualizerSettings.outputSize) {
const dataArray = [];
for (let i = 0; i < Math.min(data.length, outputSize); i++) {
dataArray[i] = data[i+offset];
}
return dataArray;
}
Also see: Tab Triggers