Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's 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 it's URL and the proper URL extention.

+ 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

Save Automatically?

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

              
                <meta charset=utf-8>
<button id=newGum>New gUM request</button>
<form>
  <label for='aec'>AEC</label>
  <input id='aec' type=checkbox>
  <label for='agc'>AGC</label>
  <input id='agc' type=checkbox>
  <label for='ns'>NS</label>
  <input id='ns' type=checkbox>
  <label for='channelCount'>ChannelCount</label>
  <input id='channelCount' type=number min=1 max=4>
</form>

              
            
!

CSS

              
                .wrapper {
  border: 1px dashed black;
  padding: 1em;
}
canvas {
  border: 1px solid gray;
}
              
            
!

JS

              
                let ac = new AudioContext();
let iframeWrappers = [];
let newGumButton = document.getElementById("newGum");
// true to log extra information about contraints
let debugLogs = false;
// true if the global audio context is used in each iframe
// false if each iframe should create its own audio context
let useGloablAudioContextInIframes = false;

function constraintsFromDOM(element) {
  let constraints = {};
  constraints.echoCancellation = element.querySelector("#aec").checked;
  constraints.autoGainControl = element.querySelector("#agc").checked;
  constraints.noiseSuppression = element.querySelector("#ns").checked;
  let channelCount = element.querySelector("#channelCount").value;
  if (channelCount) {
    constraints.channelCount = channelCount;
  }
  if (debugLogs) {
    console.log("constraints from DOM with ", constraints);
  }
  return constraints;
}

function constraintsToDOM(constraints, element) {
  if (debugLogs) {
    console.log("constraints to DOM with ", constraints);
  }
  element.querySelector("#aec").checked = constraints.echoCancellation;
  element.querySelector("#agc").checked = constraints.autoGainControl;
  element.querySelector("#ns").checked = constraints.noiseSuppression;
  if (constraints.channelCount) {
    element.querySelector("#channelCount").value = constraints.channelCount;
  }
}

function compareConstraints(oldConstraints, newConstraints) {
  let diffString = "";
  if (oldConstraints.echoCancellation != newConstraints.echoCancellation) {
    diffString += `echoCancellation changed: ${oldConstraints.echoCancellation} -> ${newConstraints.echoCancellation} `;
  }
  if (oldConstraints.autoGainControl != newConstraints.autoGainControl) {
    diffString += `autoGainControl changed: ${oldConstraints.autoGainControl} -> ${newConstraints.autoGainControl} `;
  }
  if (oldConstraints.noiseSuppression != newConstraints.noiseSuppression) {
    diffString += `noiseSuppression changed: ${oldConstraints.noiseSuppression} -> ${newConstraints.noiseSuppression} `;
  }
  if (oldConstraints.channelCount != newConstraints.channelCount) {
    diffString += `channelCount changed: ${oldConstraints.channelCount} -> ${newConstraints.channelCount} `;
  }
  if (diffString) {
    console.log(diffString.trim());
  }
}

newGumButton.onclick = async () => {
  var constraints = constraintsFromDOM(document.body);
  console.log("new gum with ", constraints);

  let iframe = document.createElement("iframe");
  iframe.width = 600;
  iframe.height = 600;
  let iframeLoadedPromise = new Promise((resolve, reject) => {
    iframe.onload = () => { resolve(); };
  });
  document.documentElement.appendChild(iframe);
  await iframeLoadedPromise;
  setUpNewIframe(iframe, constraints);
};

// For each gum, update canvases, audio graph, and log constraint changes to console
function refeshGumState() {
  for (let i = 0; i < iframeWrappers.length; i++) {
    console.log("Upating gum at index: ", i);
    let iframeWrapper = iframeWrappers[i];
    let channelCount = iframeWrapper.stream.getAudioTracks()[0].getSettings().channelCount;

    // Update canvas(es)
    let canvases = iframeWrapper.div.querySelectorAll("canvas");
    for (var j = 0; j < canvases.length; j++) {
      canvases[j].remove();
    }
    
    iframeWrapper.canvases = [];
    iframeWrapper.contexts = [];
    for (let j = 0; j < channelCount; j++) {
      let canvas = iframeWrapper.iframe.contentWindow.document.createElement("canvas");
      canvas.width = 512;
      canvas.height = 256;
      iframeWrapper.canvases.push(canvas);
      iframeWrapper.contexts.push(canvas.getContext("2d"));
      iframeWrapper.div.appendChild(canvas);
    }
    // Done updating canvas(es)

    // Update audio graph
    if (iframeWrapper.splitter) {
      iframeWrapper.analysers.forEach((e) => e.disconnect());
      iframeWrapper.splitter.disconnect();
      iframeWrapper.sourceNode.disconnect();
    }

    iframeWrapper.splitter = null;
    iframeWrapper.analysers = [];
    iframeWrapper.analysisBuffers = [];

    iframeWrapper.splitter = iframeWrapper.ac.createChannelSplitter(channelCount);
    iframeWrapper.sourceNode = iframeWrapper.ac.createMediaStreamSource(iframeWrapper.stream);
    iframeWrapper.sourceNode.connect(iframeWrapper.splitter);
    for (let j = 0; j < channelCount; j++) {
      let an = iframeWrapper.ac.createAnalyser();
      an.fftSize = iframeWrapper.canvases[j].width * 2;
      iframeWrapper.splitter.connect(an, j, 0);
      iframeWrapper.analysers.push(an);
      iframeWrapper.analysisBuffers.push(new Uint8Array(an.frequencyBinCount));
    }
    iframeWrapper.sourceNode.connect(iframeWrapper.ac.destination);
    // Done updating audio graph

    // Update form
    actualConstraints = iframeWrapper.stream.getAudioTracks()[0].getSettings();
    constraintsToDOM(actualConstraints, iframeWrapper.div);
    // Done updating form

    // Log changes in constraints
    if (iframeWrapper.prevConstraints) {
      compareConstraints(iframeWrapper.prevConstraints, actualConstraints);
    }
    iframeWrapper.prevConstraints = actualConstraints;
  }
}

async function setUpNewIframe(iframe, constraints) {
  let mediaStream;
  try {
    mediaStream = await iframe.contentWindow.navigator.mediaDevices.getUserMedia({audio: constraints});
  } catch (e) {
    // Gum failed, warn and early return!
    console.log(`Failed to gUM for new iframe with ${e}`);
    let label = iframe.contentWindow.document.createElement("label");
    label.innerHTML = "Failed to gUM in this iFrame!";
    iframe.contentWindow.document.body.appendChild(label);
    return;
  }
  const oneMic = `
    <button id=newgum>applySettings</button>
    <form>
      <label for='aec'>AEC</label>
      <input id='aec' type=checkbox>
      <label for='agc'>AGC</label>
      <input id='agc' type=checkbox>
      <label for='ns'>NS</label>
      <input id='ns' type=checkbox>
      <label for='channelCount'>ChannelCount</label>
      <input id='channelCount' type=number min=1 max=4>
    </form>`;
    let wrapperDiv = iframe.contentWindow.document.createElement("div");
    wrapperDiv.className = "wrapper";
    wrapperDiv.innerHTML = oneMic;
    let iframeWrapper= {};
    iframeWrapper.iframe = iframe;
    if (useGloablAudioContextInIframes) {
      iframeWrapper.ac = ac;
    } else {
      iframeWrapper.ac = new iframe.contentWindow.AudioContext();
    }
    iframeWrapper.div = wrapperDiv;
    iframeWrapper.stream = mediaStream;
    wrapperDiv.querySelector("button").onclick = async function() {
      let c = constraintsFromDOM(wrapperDiv);
      await iframeWrapper.stream.getAudioTracks()[0].applyConstraints(c); 
      refeshGumState();
    }
    iframe.contentWindow.document.body.appendChild(wrapperDiv);
    iframeWrappers.push(iframeWrapper);
    refeshGumState();
}

function render() {
  for (let i = 0; i < iframeWrappers.length; i++) {
    if (iframeWrappers[i].contexts.length != iframeWrappers[i].analysers.length) {
      throw `gum[${i}] has a different number of drawing contexts and analysers! This shouldn't happen!`;
    }
    for (let j = 0; j < iframeWrappers[i].contexts.length; j++) {
      let context = iframeWrappers[i].contexts[j];
      let canvas = iframeWrappers[i].canvases[j];
      let analyser = iframeWrappers[i].analysers[j];
      let buf = iframeWrappers[i].analysisBuffers[j];
      context.clearRect(0, 0, canvas.width, canvas.height);
      analyser.getByteFrequencyData(buf);
      for (let k = 0; k < canvas.width; k++) {
        context.fillRect(k * 2, canvas.height, 1, -buf[k]);
      }
    }
  }
  requestAnimationFrame(render);
}
render();
              
            
!
999px

Console