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

              
                <canvas id="responsive-canvas"></canvas>

<div id="mainControls">

<div class="centringContainer">

  <div class="table">
    
    <div class="row">
      <div class="left">
        <label for="BitDepthSlider"><strong>Bit Depth:</strong></label>
      </div>
      <div class="slidecontainer">
        <input type="range" min="1" max="16" step="1" value="16" class="slider" id="BitDepthSlider"/>
      </div>
      <div id="bitDepthText">
        <strong>16</strong> bits
      </div>
    </div>
    
  </div>

<div class="main">

  <div class="full">
    <p>
      This is an interactive demonstration of how bit depth affects digital audio. Try turning on the <strong>View digital</strong> toggle and watch what happens to the orange signal when you vary the <strong>Bit Depth</strong>.
    </p>
  </div>

  <div class="table">
    <div class="row">
      <div class="left">
        <label for="DigitalToggle"><strong>View digital:</strong></label>
      </div>
      <div class="togglecontainer">
        <label class="switch">
          <input type="checkbox" id="DigitalToggle">
          <span class="toggleSlide" id="orangeBack"></span>
        </label>
      </div>
    </div>
  </div>

  <div class="full">
    <p>
      The orange signal represents our attempt to reproduce the analogue (blue) signal given purely digital data.
    </p>
    <p>
      We do this by converting the analogue signal into a series of numbers. The bit depth we use to represent those numbers has a significant impact on the accuracy of our digital representation of the analogue signal.
    </p>
    <p>
      A higher Bit Depth means we have a more accurate signal and less digital (quantisation) noise is introduced into the signal.
    </p>
  </div>

  <div class="full">
    <p>
      Turn on audio to hear how lower bit depths affect digital audio (audio tested in Chrome and Firefox 80).
    </p>
  </div>

  <div class="table">
    <div class="row">
      <div class="left">
        <label for="AudioToggle"><strong>Toggle audio:</strong></label>
      </div>
      <div class="togglecontainer">
        <button type="button" onclick="audioToggle()" class="button" id="AudioToggle">
          <span class="material-icons">volume_off</span>
        </button>
      </div>
    </div>
  </div>

  <div class="full">
    <p>
      Quantisation noise is <em>correlated</em> noise, because the noise is <em>correlated</em> to the bit depth. While we can't remove this noise, we can mask it using <strong>dither</strong> and <strong>noise shaping</strong>. Perceptually, this increases the <strong>signal to noise ratio</strong>.
    </p>
    <p>
      Using the following 2 toggles, listen to how the distinctive quantisation noise we hear at lower bit depths disappears behind the dither and noise shaping we add to the signal.
    </p>
  </div>

  <div class="table">
    <div class="row">
      <div class="left">
        <label for="DitherToggle"><strong>Toggle dither:</strong></label>
      </div>
      <div class="togglecontainer">
        <label class="switch">
          <input type="checkbox" id="DitherToggle">
          <span class="toggleSlide"></span>
        </label>
      </div>
    </div>
    <div class="row">
      <div class="left">
        <label for="ShapingToggle"><strong>Toggle noise shaping:</strong></label>
      </div>
      <div class="togglecontainer">
        <label class="switch">
          <input type="checkbox" id="ShapingToggle">
          <span class="toggleSlide"></span>
        </label>
      </div>
    </div>
  </div>

  <div class="full">
    <h2>Definitions:</h2>
    <p>
      <strong>Dither:</strong> Adding noise to the signal before quantisation. Helps mask the very noticeable quantisation noise.
    </p>
    <p>
      <strong>Noise Shaping:</strong> Filtering the quantisation error in the signal (effectively moves the quantisation error into a portion of the spectrum where it's less noticeable).
    </p>
  </div>
  
  <div>
    <!--Add a little whitespace at the bottom.-->
    &nbsp;
  </div>

</div>

</div>
  
</div>

              
            
!

CSS

              
                @import url(//fonts.googleapis.com/icon?family=Material+Icons);
@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Spartan:wght@900&display=swap');

html {
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Open Sans', sans-serif;
  font-size: large;
  color: #44546a;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

h2 {
  font-family: 'Spartan'
}

a {
  font-weight: bold;
  /*text-decoration: none;*/
  color: #44546a;
}

a:hover {
  color: #dd7d3b;
}

.centringContainer {
  width: 96%;
	max-width: 512px;
  height: 100%;
	margin: auto;
  position: relative;
  top: 16px;
}

.main {
  height: calc(100% - 90px);
  overflow-y: auto;
  padding-left: 6px;
  padding-right: 6px;
	/*height: 100%;*/
}

.full {
	width: 100%;
	margin: auto;
	/*text-align: center;*/
	margin-bottom: 0px;
}

.table {
  display: table;
  width: 100%;
}

.row {
  display: table-row;
  height: 24px;
}

.left {
	min-width: 96px;
  height: 32px;
	text-align: right;
  display: table-cell;
  vertical-align: middle;
  /*border: 1px solid black;*/
  font-family: 'Spartan', sans-serif;
}

.slidecontainer {
  width: 50%;
  height: 32px;
  display: table-cell;
  /*border: 1px solid black;*/
  vertical-align: middle;
  padding-left: 6px;
}

#bitDepthText {
  width: 25%;
  height: 32px;
  display: table-cell;
  vertical-align: top;
  padding-left: 6px;
}

.togglecontainer {
  width: 50%;
  height: 32px;
  display: table-cell;
  /*border: 1px solid black;*/
  vertical-align: middle;
  padding-left: 6px;
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 32px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

.button {
	background: #FFFFFF;
	cursor: pointer;
	/*border: 4px solid #8496b0;
	border-radius: 50%;*/
	border: 0px;
	color: #44546a;
	width: 32px;
	height: 32px;
}
.button:hover {
	color: #8496b0;
}

.slider {
	-webkit-appearance: none;  /* Override default CSS styles */
	appearance: none;
	width: 100%; /* Full-width */
	height: 16px; /* Specified height */
	outline: none; /* Remove outline */
  background: #FFFFFF;
}

/* The slider handle (use -webkit- (Chrome, Opera, Safari, Edge) and -moz- (Firefox) to override default look) */
.slider::-webkit-slider-thumb {
	-webkit-appearance: none; /* Override default look */
	appearance: none;
	width: 16px; /* Set a specific slider handle width */
	height: 16px; /* Slider handle height */
	background: #FFFFFF;
	cursor: pointer; /* Cursor on hover */
	margin-top: -6px;
	border: 2px solid #8496b0;
	border-radius: 8px;
}

.slider::-moz-range-thumb {
	width: 16px; /* Set a specific slider handle width */
	height: 100%; /* Slider handle height */
	background: #FFFFFF;
	cursor: pointer; /* Cursor on hover */
	border-width: 2px;
	border-color: #8496b0;
	border-radius: 50%;
}

.slider::-webkit-slider-thumb:hover {
	background: #EFEFFF;
}

.slider::-moz-range-thumb:hover {
	background: #EFEFFF;
}

input[type=range]::-webkit-slider-runnable-track {
	width: 100%;
	height: 4px;
	cursor: pointer;
	background: #8496b0;
	border-radius: 2px;
}

input[type=range]::-moz-range-track {
	width: 100%;
	height: 4px;
	cursor: pointer;
	background: #8496b0;
	border-radius: 2px;
}

#responsive-canvas {
  width: 100%; /*Necessary to ensure our canvas fits horizontally.*/
}

/* The switch - the box around the slider */
.switch {
  position: relative;
  display: inline-block;
  width: 48px;
  height: 24px;
  margin-left: 2px;
  /*margin-top: 2px;
  margin-bottom: 2px;*/
}

/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* The toggle slider */
.toggleSlide {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 24px;
}

.toggleSlide:before {
  position: absolute;
  content: "";
  width: 18px;
  height: 18px;
  left: 4px;
  bottom: 3.5px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 24px;
}

input:checked + .toggleSlide {
  background-color: #44546a;
}

input:checked + #orangeBack {
  background-color: #dd7d3b;
}

/*input:focus + .toggleSlide {
  box-shadow: 0 0 1px #8496b0;
}*/

input:checked + .toggleSlide:before {
  -webkit-transform: translateX(22px);
  -ms-transform: translateX(22px);
  transform: translateX(22px);
}

              
            
!

JS

              
                //Get canvas for setting internal resolution.
var canvas = document.getElementById('responsive-canvas');
//Our main div.
var mainDiv = document.getElementById('mainControls');

//Get our on-screen controls.
var bitDepthSlider = document.getElementById("BitDepthSlider");
var digitalToggle = document.getElementById("DigitalToggle");
var ditherToggle = document.getElementById("DitherToggle");
var shapingToggle = document.getElementById("ShapingToggle");

var frequency = 3.0;

//True if audio is running.
var audioRunning = false;

var aliasingGenNode;

bitDepthSlider.oninput = bitDepthSliderChange;
digitalToggle.onchange = digitalToggleChange;
ditherToggle.onchange = ditherToggleChange;
shapingToggle.onchange = shapingToggleChange;

window.onresize = resize;
resize();
draw();

//Helper function for getting a URL for a string/code.
function getURLFromInlineCode(code) {
  const codeBlob = new Blob(code, {type: 'application/javascript'});
  
  return URL.createObjectURL(codeBlob);
}

//Our custom audio processor, encapsulated in a URL.
const bitDepthGenURL = getURLFromInlineCode`
class BitDepthGenerator extends AudioWorkletProcessor {

  static get parameterDescriptors () {
    return [{
      name: 'bitDepth',
      defaultValue: 16,
      minValue: 1,
      maxValue: 16,
      automationRate: 'a-rate'
    },
    {
      name: 'noiseShaping',
      defaultValue: 0,
      minValue: 0,
      maxValue: 1,
      automationRate: 'k-rate'
    },
    {
      name: 'dither',
      defaultValue: 0,
      minValue: 0,
      maxValue: 1,
      automationRate: 'k-rate'
    },
    {
      name: 'amplitude',
      defaultValue: 1,
      minValue: 0,
      maxValue: 1,
      automationRate: 'a-rate'
    }]
  }

  constructor() {
    super();

    this.sinIndex = 0.0;
    this.lastErr = 0.0;
  }

  //Generate our audio.
  process(inputs, outputs, parameters) {
    const sinInc = (440.0/sampleRate) * 2.0 * Math.PI;
    var noiseShaping = parameters['noiseShaping'][0];
    var dither = parameters['dither'][0];

    for(let i=0;i<outputs[0].length;++i) {
      const buffer = outputs[0][i];

      if(i == 0) {
        for(let j=0;j<buffer.length;++j) {
          var bitDepth = (parameters['bitDepth'].length > 1) ? parameters['bitDepth'][i] : parameters['bitDepth'][0];
          var amp = (parameters['amplitude'].length > 1) ? parameters['amplitude'][i] : parameters['amplitude'][0];

          var maxVal = Math.floor(Math.pow(2.0, bitDepth)) - 1;

          var sampleVal = Math.sin(this.sinIndex);
          this.sinIndex += sinInc;
          this.sinIndex %= (2.0 * Math.PI);

          //sampleVal now 0 -> 1.
		      sampleVal = (sampleVal + 1.0) * 0.5;

          //sampleVal now 0 -> 2^bitDepth.
		      sampleVal *= maxVal;

          //Add dither if necessary.
          if(dither) {
            var randInt = Math.floor(Math.random() * Math.floor(3));
            switch(randInt) {
              case 0:
                sampleVal += 1.0;
                break;
              case 1:
                sampleVal -= 1.0;
                break;
            }

            if(sampleVal < 0.0)
              sampleVal = 0.0;
            else if(sampleVal >= maxVal)
              sampleVal = maxVal;
          }
 
          //Add noise shaping if necessary.
          if(noiseShaping)
            sampleVal += this.lastErr * 0.99;

          //Quantise sampleVal.
          var unquantisedVal = sampleVal;
          sampleVal = Math.round(sampleVal);

          //Update last quantisation error.
          this.lastErr = unquantisedVal - sampleVal;

          //sampleVal now 0 -> 1 again.
          sampleVal /= maxVal;

          //sampleVal now -1 -> +1 again.
          sampleVal = (sampleVal * 2.0) - 1.0;

          sampleVal *= amp;
          buffer[j] = sampleVal;
        }
      }
      else {
        //We're mono, but if we find ourselves working in stereo, just copy channel 0.
        buffer[0][i] = buffer[0][0].slice();
      }
    }

    return true;
  }
}

registerProcessor('BitDepthGen', BitDepthGenerator);
`

//Node for our audio processor.
class BitDepthGenNode extends AudioWorkletNode {
  constructor(context) {
    super(context, 'BitDepthGen');
  }
}

//Used to resize our canvas when the window's resized.
function resize() {
  canvas.width = window.innerWidth * window.devicePixelRatio;
  //console.log("window.innerWidth: ", window.innerWidth * window.devicePixelRatio);

  //Set canvas height as a proportion of width.
  /*var height = canvas.width * 0.5;
  if(height > 320)
    height = 320;
  canvas.height = height;*/
  canvas.height = 320;
	
	var h = window.innerHeight - (canvas.height / window.devicePixelRatio);
	h += "px";
	mainDiv.style.height = h;
  
  draw();
}

//Used to redraw the canvas when necessary.
function draw() {
  //Start drawing.
  const canvasContext = canvas.getContext('2d');
  const centreY = canvas.height/2;
  const sinHeight = centreY - 8;
  
  canvasContext.fillStyle = 'white';
  canvasContext.fillRect(0, 0, canvas.width, canvas.height);

  canvasContext.strokeStyle = '#44546A';
  canvasContext.lineWidth = 4;
  
  var numPeriods = frequency;
  var periodLength = (canvas.width/numPeriods);
  var halfLength = (periodLength * 0.5);
  
  canvasContext.translate(-(0.5 * halfLength), 0);
  
  canvasContext.beginPath();
  canvasContext.moveTo(0, centreY + sinHeight);
  
  for(let i=0;i<(numPeriods + 1);++i) {
    var x = (i * periodLength);
    
    canvasContext.bezierCurveTo(x + (halfLength * 0.3634),
                                centreY + sinHeight,
                                x + (halfLength * 0.6366),
                                centreY - sinHeight,
                                x + halfLength,
                                centreY - sinHeight);
    x += halfLength;
    canvasContext.bezierCurveTo(x + (halfLength * 0.3634),
                                centreY - sinHeight,
                                x + (halfLength * 0.6366),
                                centreY + sinHeight,
                                x + halfLength,
                                centreY + sinHeight);
  }
  canvasContext.stroke();
  
  canvasContext.translate((0.5 * halfLength), 0);
  
  //Calculate samples.
  if(digitalToggle.checked) {
    var numSamples = 128;
    var bitDepth = bitDepthSlider.value;
    
    if((bitDepth > 5) && (bitDepth < 10))
        numSamples = 512;

    var sampleDist = canvas.width/numSamples;

    var pos = {x: 0.0, y: centreY};
    var sinInc = (frequency * 2.0 * Math.PI)/numSamples;
    var sinIndex = 0.0;
    var lastErr = 0.0;
    
    //Bit of a cheat to ensure the v. quantised signal is centred on the original sine wave.
    if(bitDepth < 9)
      sinIndex = sinInc * 0.5;
    
    var lastY;

    canvasContext.strokeStyle = '#DD7D3B';
    canvasContext.beginPath();

    var noiseShaping = shapingToggle.checked;
    var dither = ditherToggle.checked;

    var maxVal = Math.floor(Math.pow(2.0, bitDepth)) - 1;

    for(var i=0;i<(numSamples + 2);++i) {

      var sampleVal = -Math.sin(sinIndex);
      sinIndex += sinInc;
      sinIndex %= (2.0 * Math.PI);

      //sampleVal now 0 -> 1.
      sampleVal = (sampleVal + 1.0) * 0.5;

      //sampleVal now 0 -> 2^bitDepth.
      sampleVal *= maxVal;

      //Add dither if necessary.
      if(dither) {
        var randInt = Math.floor(Math.random() * Math.floor(3));
        switch(randInt) {
          case 0:
            sampleVal += 1.0;
            break;
          case 1:
            sampleVal -= 1.0;
            break;
        }

        if(sampleVal < 0.0)
          sampleVal = 0.0;
        else if(sampleVal >= maxVal)
          sampleVal = maxVal;
      }

      //Add noise shaping if necessary.
      if(noiseShaping)
        sampleVal += lastErr * 0.99;

      //Quantise sampleVal.
      var unquantisedVal = sampleVal;
      sampleVal = Math.round(sampleVal);

      //Update last quantisation error.
      lastErr = unquantisedVal - sampleVal;

      //sampleVal now 0 -> 1 again.
      sampleVal /= maxVal;

      //sampleVal now -1 -> +1 again.
      sampleVal = (sampleVal * 2.0) - 1.0;
      
      //console.log(sampleVal);

      pos.y = centreY + (sampleVal * sinHeight);
      
      if(i == 0)
        canvasContext.moveTo(pos.x, pos.y);
      else {
        if((bitDepth < 9) && (Math.abs(pos.y - lastY) > 0.01))
          canvasContext.lineTo(pos.x, lastY);

        canvasContext.lineTo(pos.x, pos.y);
      }
      
      lastY = pos.y;
      pos.x += sampleDist;
    }
    canvasContext.stroke();
  }
}

function bitDepthSliderChange() {
  var bitDepthText = document.getElementById("bitDepthText");
  var bitDepth = bitDepthSlider.value;
  
  if(bitDepthSlider.value < 2)
    bitDepthText.innerHTML = "<strong>" + bitDepthSlider.value.toString() + "</strong> bit";
  else
    bitDepthText.innerHTML = "<strong>" + bitDepthSlider.value.toString() + "</strong> bits";

  const canvasContext = canvas.getContext('2d');
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  draw();
  
  if(audioRunning) {
    bitDepthGenNode.parameters.get('bitDepth').setValueAtTime(bitDepth, audioContext.currentTime);
  }
}

function digitalToggleChange() {
  const canvasContext = canvas.getContext('2d');
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  draw();
}

function ditherToggleChange() {
  const canvasContext = canvas.getContext('2d');
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  draw();
  
  if(audioRunning) {
    if(ditherToggle.checked)
      bitDepthGenNode.parameters.get('dither').setValueAtTime(1.0, audioContext.currentTime);
    else
      bitDepthGenNode.parameters.get('dither').setValueAtTime(0.0, audioContext.currentTime);
  }
}

function shapingToggleChange() {
  const canvasContext = canvas.getContext('2d');
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  draw();
  
  if(audioRunning) {
    if(shapingToggle.checked)
      bitDepthGenNode.parameters.get('noiseShaping').setValueAtTime(1.0, audioContext.currentTime);
    else
      bitDepthGenNode.parameters.get('noiseShaping').setValueAtTime(0.0, audioContext.currentTime);
  }
}

//Used to toggle our audio on and off.
//Function must be async in order to use await on audioWorklet.addModule().
async function audioToggle() {
  if(!audioRunning) {
    //Create web audio api context.
    audioContext = new (window.AudioContext || window.webkitAudioContext)();

    //Add our custom audio processor class.
    //addModule() returns a promise, so we have to await until it's fulfilled.
    await audioContext.audioWorklet.addModule(bitDepthGenURL);

    //Create an instance of our custom audio processor class.
    bitDepthGenNode = new BitDepthGenNode(audioContext);
    
    bitDepthGenNode.parameters.get('amplitude').setValueAtTime(0.0, audioContext.currentTime);
    bitDepthGenNode.parameters.get('amplitude').linearRampToValueAtTime(0.66, audioContext.currentTime + 0.25);

    //Connect our nodes to the audio context.
    bitDepthGenNode.connect(audioContext.destination);
    
    audioRunning = true;
    
    //Update audio button.
    document.getElementById("AudioToggle").innerHTML = "<span class='material-icons'>volume_up</span>";
  }
	else {
    //Stops the audio, releases any audio resources used.
		audioContext.close();
		
		audioRunning = false;
    
    //Update audio button.
    document.getElementById("AudioToggle").innerHTML = "<span class='material-icons'>volume_off</span>";
	}
}

              
            
!
999px

Console