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. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

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

              
                <div class="container-fluid top">
  <div class="row">
    <div class="col-xs-5 col-sm-4 col-md-3">
      <button id="toggleSound" class="btn btn-default"><i id="speaker" class="fa fa-volume-up fa-1x fa-fw"></i><span id="toggleLabel">Start!</span></button>
      <div class="btn-group">
        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
          Select Sound Wave <span class="caret"></span>
        </button>
        <ul id="waveDropdown" class="dropdown-menu" role="menu">
          <li><a id="sine">Sine</a></li>
          <li><a id="square">Square</a></li>
          <li><a id="sawtooth">Sawtooth</a></li>
          <li><a id="triangle">Triangle</a></li>
          <li><a tabindex="0" id="custom" title="" data-toggle="modal" data-target="#fourierModal" data-placement="bottom" data-content="Click to share this unique pattern" data-trigger="focus">Custom...</a></li>
        </ul>
      </div>
    </div>
    <div class="slider col-xs-4 col-sm-4 col-md-3">
      <label for="frequencySlider">Frequency: <span id="frequency">440</span>Hz</label>
      <input type="range" id="frequencySlider">
    </div>
  </div> 
</div>   
<canvas id="theCanvas" width="1024" height="256"></canvas>
<div id="fourierModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="fourierModal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3>Combine three different octaves</h3>
        Set Fourier Series Coefficients by entering a percentage for sine components (cos are all set to 0). Sum of all three should be 100.
      </div>
      <div class="modal-body">
        <div class="form-horizontal">
          <div class="form-group">
            <label for="first" class="col-xs-6 control-label">Base frequency (as set with the slider):</label>
            <div class="col-xs-6">
              <input id="first" type="number" class="form-control"/>
            </div>
          </div>
          <div class="form-group">
            <label for="second" class="col-xs-6 control-label">One octave up:</label>
            <div class="col-xs-6">
              <input id="second" type="number" class="form-control" />
            </div>
          </div>
          <div class="form-group">
            <label for="third" class="col-xs-6 control-label">Two octaves up:</label>
            <div class="col-xs-6">
              <input id="third" type="number" class="form-control" />
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default"><a href="http://en.wikipedia.org/wiki/Fourier_series" target="_blank"><i class="fa fa-question-circle fa-fw"></i>Help</a></button>
        <button type="button" class="btn btn-primary" id="applyButton">Apply</button>  
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
              
            
!

CSS

              
                @import url(https://fonts.googleapis.com/css?family=Jaldi);

html, * {
  font-family: 'Jaldi', sans-serif; 
}

.top {
  margin-top: 10px;
  margin-bottom: 20px;
}

.hidden {
  display: none;  
}



/*
  Slider CSS style by Aron Woost
  https://codepen.io/aronwoost/pen/nlyrf
*/

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}


.slider {
  width: 400px;
}

input[type="range"] {
  -webkit-appearance: none;
  -webkit-tap-highlight-color: rgba(255, 255, 255, 0);
  width: 100%;
  height: 20px;
  margin: 0;
  border: none;
  padding: 1px 2px;
  border-radius: 14px;
  background: #232528;
  box-shadow: inset 0 1px 0 0 #0d0e0f, inset 0 -1px 0 0 #3a3d42;
  -webkit-box-shadow: inset 0 1px 0 0 #0d0e0f, inset 0 -1px 0 0 #3a3d42;
  outline: none; /* no focus outline */
}

input[type="range"]::-moz-range-track {
  border: inherit;
  background: transparent;
}

input[type="range"]::-ms-track {
  border: inherit;
  color: transparent; /* don't drawn vertical reference line */
  background: transparent;
}

input[type="range"]::-ms-fill-lower,
input[type="range"]::-ms-fill-upper {
  background: transparent;
}

input[type="range"]::-ms-tooltip {
  display: none;
}

/* thumb */

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 40px;
  height: 18px;
  border: none;
  border-radius: 12px;
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #529de1), color-stop(100%, #245e8f)); /* android <= 2.2 */
  background-image: -webkit-linear-gradient(top , #529de1 0, #245e8f 100%); /* older mobile safari and android > 2.2 */;
  background-image: linear-gradient(to bottom, #529de1 0, #245e8f 100%); /* W3C */
}
input[type="range"]::-moz-range-thumb {
  width: 40px;
  height: 18px;
  border: none;
  border-radius: 12px;
  background-image: linear-gradient(to bottom, #529de1 0, #245e8f 100%); /* W3C */
}

input[type="range"]::-ms-thumb {
  width: 40px;
  height: 18px;
  border-radius: 12px;
  border: 0;
  background-image: linear-gradient(to bottom, #529de1 0, #245e8f 100%); /* W3C */
}
              
            
!

JS

              
                /*
  Johan Karlsson (DonKarlssonSan)

  Read my blog post about Web Audio API:
  https://codepen.io/DonKarlssonSan/blog/fun-with-web-audio-api
  
  Browser support for Web Audio API:
  http://caniuse.com/#feat=audio-api
  
  Fourier Series:
  http://en.wikipedia.org/wiki/Fourier_series
  
  Octave:
  http://en.wikipedia.org/wiki/Octave
*/
(function() {
  var AudioContext;
  var audioContext;
  var oscillator;
  var gainNode;
  var analyser;
  var isPlaying = false;  
  var canvas = document.getElementById("theCanvas");
  var canvasContext = canvas.getContext("2d");    
  var dataArray;
  var analyserMethod = "getByteTimeDomainData";
  var frequencySlider = document.getElementById("frequencySlider");
  // Fourier Coefficients used for the custom wave
  var first = 33;
  var second = 33;
  var third = 33;

  var canvasWidth = canvas.width;
  var canvasHeight = canvas.height;

  function initAudio() {
    AudioContext = window.AudioContext || window.webkitAudioContext;
    audioContext = new AudioContext();
    // The oscillator creates the sound waves.
    // As you can see on the canvas when drawing
    // the square wave, the wave is not perfectly
    // square. What you see is the Gibbs phenomenon
    // caused by the oscillator using Fourier series
    // to approximate the different wave types.
    oscillator = audioContext.createOscillator();
    oscillator.type = "sine";
    // The tone A
    // http://en.wikipedia.org/wiki/A440_(pitch_standard)
    oscillator.frequency.value = 440;
    oscillator.start(0);
    // Controls the volume
    gainNode = audioContext.createGain();
    gainNode.gain.value = 0;
    oscillator.connect(gainNode);
    // Provides info about the sound playing
    analyser = audioContext.createAnalyser();            
    gainNode.connect(analyser);
    gainNode.connect(audioContext.destination);
    
    // Oscillator -- Gain +-- Out (speaker/phones)  
    //                    |   
    //                    +-- Analyser    
  };

  function startDrawing() {
    analyser.fftSize = 2048;
    var bufferLength = analyser.frequencyBinCount;
    dataArray = new Uint8Array(bufferLength);
    canvasContext.lineWidth = 1;
    canvasContext.strokeStyle = 'rgba(0, 0, 0, 1)';
    function drawAgain() {
      canvasContext.clearRect(0, 0, canvasWidth, canvasHeight);
      requestAnimationFrame(drawAgain);

      analyser[analyserMethod](dataArray);
      for(var i = 0; i < bufferLength; i++){
        canvasContext.beginPath();
        canvasContext.moveTo(i, 255);
        canvasContext.lineTo(i, 255 - dataArray[i]);
        canvasContext.closePath();
        canvasContext.stroke();
      }
    }

    drawAgain();
  }
  
  var speakerIcon = document.getElementById("speaker");
  var toggleLabel = document.getElementById("toggleLabel");

  function toggleSound () {
    if(isPlaying) {
      speakerIcon.classList.remove("fa-volume-off");
      speakerIcon.classList.add("fa-volume-up");
      gainNode.gain.value = 0;
      toggleLabel.innerHTML = "Start!";
      isPlaying = false;
    } else {
      speakerIcon.classList.remove("fa-volume-up");
      speakerIcon.classList.add("fa-volume-off");
      gainNode.gain.value = 1;
      toggleLabel.innerHTML = "Stop!"
      isPlaying = true;
    }
  }

  document.getElementById("toggleSound").addEventListener("click",
    toggleSound, false);

  // Fourier series
  function customWave(first, second, third) {
    document.getElementById("first").value = first;
    document.getElementById("second").value = second;
    document.getElementById("third").value = third;
    // You could create several oscillator nodes with different
    // frequencies and then combine them. But here we use a
    // PeriodicWave to combine the first three sin components.
    // https://developer.mozilla.org/en-US/docs/Web/API/PeriodicWave
    var real = new Float32Array(4);
    var imag = new Float32Array(4);
    // a0 (or DC offset)
    real[0] = 0;
    imag[0] = 0;
    
    // First term. The frequency, f, set on the oscillator.
    // sin
    real[1] = first/100;
    // cos 
    imag[1] = 0;

    // Second term, f * 2, one octave up. 
    // sin
    real[2] = second/100;
    // cos 
    imag[2] = 0;

    // Third term, f * 3, two octaves up.
    // sin
    real[3] = third/100;
    // cos 
    imag[3] = 0;

    var wave = audioContext.createPeriodicWave(real, imag);
    // "the browser performs an inverse Fourier transform to 
    // get a time domain buffer for the frequency of the 
    // oscillator" -MDN
    oscillator.setPeriodicWave(wave);  
  }

  function applyClicked() {
    first = parseInt(document.getElementById("first").value);
    second = parseInt(document.getElementById("second").value);
    third = parseInt(document.getElementById("third").value);
    customWave(first, second, third);
  }
  document.getElementById("applyButton").addEventListener("click",
    applyClicked, false);

  function waveDropdownClicked (event) {
    event = event || window.event;
    var target = event.target || event.srcElement;
    if(target.nodeName === "A") {
      var waveType = target.id;
      console.log(waveType);
      oscillator.type = waveType;
      if(waveType === "custom") {
        customWave(first, second, third);
      }
    }
  };

  document.getElementById("waveDropdown").addEventListener("click", 
    waveDropdownClicked, false);

  frequencySlider.min = 5;
  frequencySlider.max = 10000;
  frequencySlider.value = 440;
  frequencySlider.step = 1;
  frequencySlider.addEventListener("change", function () {
    oscillator.frequency.value = this.value; 
    document.getElementById("frequency").innerHTML = this.value;
  });
  frequencySlider.addEventListener("mousemove", function () {
    oscillator.frequency.value = this.value; 
    document.getElementById("frequency").innerHTML = this.value;
  });

  initAudio();
  startDrawing();
})();
              
            
!
999px

Console