From 9f47e8c67e4bbf228bb9526143fe043703157b7d Mon Sep 17 00:00:00 2001 From: Lewis Moten Date: Tue, 30 Apr 2024 22:46:35 -0400 Subject: [PATCH] graph amplitude over time. --- index.html | 1 + index.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/index.html b/index.html index 4b9c8f3..affdba8 100644 --- a/index.html +++ b/index.html @@ -20,6 +20,7 @@

Received


+ diff --git a/index.js b/index.js index d1bb735..6e92c9b 100644 --- a/index.js +++ b/index.js @@ -5,6 +5,9 @@ var microphoneStream; var microphoneNode; var analyser; var receivedDataTextarea; +var receivedGraph; +var receivedData = []; +var MAX_DATA_POINTS = 1024; var FREQUENCY_TONE = 500; @@ -13,6 +16,7 @@ function handleWindowLoad() { sendButton = document.getElementById('send-button'); isListeningCheckbox = document.getElementById('is-listening-checkbox'); receivedDataTextarea = document.getElementById('received-data'); + receivedGraph = document.getElementById('received-graph'); // wire up events sendButton.addEventListener('click', handleSendButtonClick); @@ -78,6 +82,11 @@ function analyzeAudio() { var frequencyIndex = Math.round(FREQUENCY_TONE / (audioContext.sampleRate / analyser.fftSize)); const amplitude = frequencyData[frequencyIndex]; + receivedData.unshift(amplitude); + if(receivedData.length > MAX_DATA_POINTS) { + receivedData.length = MAX_DATA_POINTS; + } + drawReceivedData(); if(amplitude > 0) { receivedDataTextarea.value = `Frequency Detected. Amplitude: ${amplitude}`; } else { @@ -87,5 +96,27 @@ function analyzeAudio() { requestAnimationFrame(analyzeAudio); } +function drawReceivedData() { + const ctx = receivedGraph.getContext('2d'); + const { width, height } = receivedGraph; + const segmentWidth = (1 / MAX_DATA_POINTS) * width; + ctx.clearRect(0, 0, width, height); + const sorted = receivedData.slice().sort((a, b) => a - b); + const min = sorted[0]; + const max = sorted[sorted.length - 1]; + const range = max - min; + ctx.beginPath(); + for(let i = 0; i < MAX_DATA_POINTS && i < receivedData.length; i++) { + const value = receivedData[i]; + const y = (1-(value / range)) * height; + if(i === 0) { + ctx.moveTo(0, y); + } else { + ctx.lineTo(segmentWidth * i, y) + } + } + ctx.stroke(); +} + window.addEventListener('load', handleWindowLoad); \ No newline at end of file