A simple oscillator node

A minimal example using an oscillator node as a source. In this example, the first meter visualizes the level of the gainNode and the second meter visualizes the level of the panNode.

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>
<div>
  <input type="range" id="gain" name="gain" min="0" max="1" value="0" step="0.05">
  <label for="gain">Gain</label>
</div>
<div id="peak-meter-1" style="height: 60px; margin-bottom: 20px;"></div>
<div>
  <input type="range" id="panning" name="panning" min="-1" max="1" value="0" step="0.1">
  <label for="panning">Pan</label>
</div>
<div id="peak-meter-2" style="height: 60px;"></div>

Javascript code

const audioCtx = new AudioContext();

const ctxStatus = document.getElementById('ctx-status');
setInterval(() => {
  ctxStatus.innerText = audioCtx.state;
  if (audioCtx.state === 'suspended') {
    buttonElement.innerText = 'Resume';
  } else {
    buttonElement.innerText = 'Suspend';
  }
}, 100);

const buttonElement = document.getElementById('ctx-button');
buttonElement.addEventListener('click', () => {
  if (audioCtx.state === 'suspended') {
    audioCtx.resume();
  } else {
    audioCtx.suspend();
  }
});

const oscillatorNode = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
const panNode = audioCtx.createStereoPanner();

oscillatorNode.type = 'sine';
oscillatorNode.frequency.setValueAtTime(440, audioCtx.currentTime);
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
panNode.pan.setValueAtTime(0, audioCtx.currentTime);
oscillatorNode.connect(gainNode);
gainNode.connect(panNode);
panNode.connect(audioCtx.destination);
oscillatorNode.start();

const meterElement1 = document.getElementById('peak-meter-1');
const meter1 = new webAudioPeakMeter.WebAudioPeakMeter(gainNode, meterElement1);
const meterElement2 = document.getElementById('peak-meter-2');
const meter2 = new webAudioPeakMeter.WebAudioPeakMeter(panNode, meterElement2);

const gainSlider = document.getElementById('gain');
gainSlider.addEventListener('change', (evt) => {
  gainNode.gain.setValueAtTime(evt.target.value, audioCtx.currentTime);
});

const panningSlider = document.getElementById('panning');
panningSlider.addEventListener('change', (evt) => {
  panNode.pan.setValueAtTime(evt.target.value, audioCtx.currentTime);
});