Usage without a DOM node

For users who desire the metering functionality of this library but not the visual presentation, it’s possible to create an instance without providing a DOM node as a second argument.

To get the peaks at the current moment, as well as the maximum values for each channel, since the last time clearPeaks() was called, call the instance’s getPeaks() method.

Working Example

The web audio API context is loading.

HTML code

<p>
  The web audio API context is <span id="ctx-status">loading</span>.
  <button id="ctx-button">Loading</button>
</p>

<audio id="the-audio" preload="metadata" crossorigin="anonymous" controls="controls">
  <source src="https://assets.rpy.xyz/testmedia/semper_fidelis.mp3" type="audio/mpeg" />
</audio>
<div>
  <button id="clear-peaks">Clear Peaks</button>
  <button id="get-peaks">Get Peaks</button>
</div>
<ul>
  <li>Current peaks (floating point): <span id="current-float"></span></li>
  <li>Current peaks (decibels): <span id="current-db"></span></li>
  <li>Channel maxes (floating point): <span id="maxes-float"></span></li>
  <li>Channel maxes (decibels): <span id="maxes-db"></span></li>
</ul>

Javascript code

const audioCtx = new AudioContext();
const audioElement = document.getElementById('the-audio');
const clearPeaks = document.getElementById('clear-peaks');
const getPeaks = document.getElementById('get-peaks');
const currentFloat = document.getElementById('current-float');
const currentDB = document.getElementById('current-db');
const maxesFloat = document.getElementById('maxes-float');
const maxesDB = document.getElementById('maxes-db');

const sourceNode = audioCtx.createMediaElementSource(audioElement);
sourceNode.connect(audioCtx.destination);

const ctxStatus = document.getElementById('ctx-status');
const buttonElement = document.getElementById('ctx-button');

function updateAudioCtxStatus() {
  ctxStatus.innerText = audioCtx.state;
  if (audioCtx.state === 'suspended') {
    buttonElement.innerText = 'Resume';
  } else {
    buttonElement.innerText = 'Suspend';
  }
}

setInterval(updateAudioCtxStatus, 1000);

buttonElement.addEventListener('click', () => {
  if (audioCtx.state === 'suspended') {
    audioCtx.resume().then(updateAudioCtxStatus);
  } else {
    audioCtx.suspend().then(updateAudioCtxStatus);
  }
});

const meterInstance = new webAudioPeakMeter.WebAudioPeakMeter(sourceNode);

clearPeaks.addEventListener('click', () => {
  meterInstance.clearPeaks();
});

const displayFloatArray = (arr) => arr.map((val) => val.toFixed(2)).join(', ');

getPeaks.addEventListener('click', () => {
  const peaks = meterInstance.getPeaks();
  currentFloat.innerText = displayFloatArray(peaks.current);
  currentDB.innerText = displayFloatArray(peaks.currentDB);
  maxesFloat.innerText = displayFloatArray(peaks.maxes);
  maxesDB.innerText = displayFloatArray(peaks.maxesDB);
});