- Joined
- Jan 2, 2020
- Messages
- 1,414
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 :
If you want a live demonstration you can put this into a textfile and rename to runme.html
Here's a screenshot :
If you want a live demonstration you can put this into a textfile and rename to runme.html
Code:
<!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>