Created
September 26, 2024 18:03
-
-
Save llimllib/e124b56b31264c512911b0826ee05955 to your computer and use it in GitHub Desktop.
minimal web spectrometer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>Frequency Domain Visualization</title> | |
<style> | |
canvas { | |
border: 1px solid black; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="spectro" width="800" height="400"></canvas> | |
<script src="tuner.js"></script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get the canvas element and its context | |
const canvas = document.getElementById("spectro"); | |
const ctx = canvas.getContext("2d"); | |
// Create an AudioContext | |
const audioCtx = new AudioContext(); | |
async function main() { | |
const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); | |
const source = audioCtx.createMediaStreamSource(stream); | |
const analyser = audioCtx.createAnalyser(); | |
source.connect(analyser); | |
const bufferLength = analyser.frequencyBinCount; | |
const dataArray = new Uint8Array(bufferLength); | |
function draw() { | |
// Clear the canvas | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
// Get the frequency data and draw it on the canvas | |
analyser.getByteFrequencyData(dataArray); | |
const barWidth = canvas.width / bufferLength; | |
let x = 0; | |
for (let i = 0; i < bufferLength; i++) { | |
const barHeight = (dataArray[i] / 255) * canvas.height; | |
ctx.fillRect(x, canvas.height - barHeight, barWidth, barHeight); | |
x += barWidth; | |
} | |
// Request the next animation frame | |
requestAnimationFrame(draw); | |
} | |
// Start the animation loop | |
draw(); | |
} | |
main() | |
.then() | |
.catch((e) => console.error(e)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment