JSFiddle - React, Tailwind, and code Playground

by replicateur

HTML

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<title>JS Bin</title>

<body>
  <button id="start">Play the sound</button>
  <button id="stop">Stop the sound</button>
  <canvas id='scope'></canvas>
  <div id="console"></div>
  <input class="graphsize" type="range" min="20" max="90" value="75" />
</body>

CSS

#scope {
  margin: 1em;
}

JavaScript

//setup audio context
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new window.AudioContext();
var graphSize = 75;
var lineWidth = 3;

//create nodes
var osc; //create in event listener so we can press the button more than once
var masterGain = context.createGain();
var analyser = context.createAnalyser();

//routing
masterGain.connect(analyser);
analyser.connect(context.destination);

var isPlaying = false;

//draw function for canvas
function drawWave(analyser, ctx) {

  var buffer = new Float32Array(1024),
    w = ctx.canvas.width;
  h = ctx.canvas.height;

  ctx.strokeStyle = "darkgrey";
  ctx.setTransform(1, 0, 0, -1, 0, h / 2); // flip y-axis and translate to center
  ctx.lineWidth = lineWidth;

  (function loop() {
    analyser.getFloatTimeDomainData(buffer);

    ctx.clearRect(0, -100, w, ctx.canvas.height);

    ctx.beginPath();
    ctx.moveTo(0, buffer[0] * graphSize);
    for (var x = 2; x < w; x += 2) {
      ctx.lineTo(x, buffer[x] * graphSize);
    }
    ctx.stroke();

    if (isPlaying) requestAnimationFrame(loop)
  })();
}

document.addEventListener('input', changeGraphSize, false);

function changeGraphSize(event) {
  if (event !== "undefined" &&
    event.target !== "undefined" &&
    event.target.value !== "undefined") {
    graphSize = event.target.value
  }
}

//button trigger
$(function() {
  var c = document.getElementById('scope'),
    ctx = c.getContext("2d");

  c.height = 200;
  c.width = 600;

  // make 0-line permanent as background
  ctx.moveTo(0, ctx.canvas.height / 2);
  ctx.lineTo(ctx.canvas.width, ctx.canvas.height / 2);
  ctx.stroke();
  c.style.backgroundColor = "lightgrey";

  $('#start').on('mousedown', function() {
    osc = context.createOscillator();
    //osc settings
    osc.frequency.value = 220;
    var imag = new Float32Array([0, 0, 1, 0, 1]); // sine
    var real = new Float32Array(imag.length); // cos
    var customWave = context.createPeriodicWave(real, imag); // cos,sine
   ...