A sound idea!

Jimmy

Active Member
Tutorial Author
Joined
Jan 2, 2020
I'm trying to understand how to make a sound through a oscilloscope using CX. I'm a simple web programmer though so can someone guide me how to make something like this into CX please?

Here's a screenshot :

osc screenshot.png


If you want a live demonstration you can put this into a textfile and rename to runme.html

HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<canvas width="512" height="256" id="canvas"></canvas>
<script>

let audioContext;
let analyser;
let canvas;
let canvasContext;

let constraints = { audio: true };
navigator.mediaDevices.
getUserMedia(constraints).
then(stream => {
  initAudio(stream);
  initGraphics();
  startDrawing();
}).catch(err => {
  console.log(err);
});

function initAudio(stream) {
  audioContext = new (window.AudioContext || window.webkitAudioContext)();
  let mediaStreamSource = audioContext.createMediaStreamSource(stream);
  analyser = audioContext.createAnalyser();
  analyser.smoothingTimeConstant = 0.9;
  mediaStreamSource.connect(analyser);
}

function initGraphics() {
  canvas = document.getElementById("canvas");
  canvasContext = canvas.getContext("2d");
}

function startDrawing() {
  analyser.fftSize = 1024;
  let bufferLength = analyser.frequencyBinCount;
  let dataArray = new Uint8Array(bufferLength);
  canvasContext.lineWidth = 2;

  function draw() {
    canvasContext.clearRect(0, 0, canvas.width, canvas.height);
    requestAnimationFrame(draw);
    analyser.getByteTimeDomainData(dataArray);
    canvasContext.beginPath();
    for (let x = 0; x < bufferLength; x++) {
      let y = 255 - dataArray[x];
      canvasContext.lineTo(x, y);
    }
    canvasContext.closePath();
    canvasContext.stroke();
  }
  draw();
}

</script>
</body>
</html>
 

Jimmy

Active Member
Tutorial Author
Joined
Jan 2, 2020
Thanks, I'll take a look! You can do as complex sound as you wish on the fly with JavaScript, There might still be some kind of (low) latency of course, you could not easily create online professional music software just yet but it's getting there. Very inspirational.
 
Top Bottom