|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 6 | + <title>Audio Spectrum Visualizer</title> |
| 7 | + <style> |
| 8 | + body { |
| 9 | + display: flex; |
| 10 | + justify-content: center; |
| 11 | + align-items: center; |
| 12 | + height: 100vh; |
| 13 | + margin: 0; |
| 14 | + background-color: #f0f0f0; |
| 15 | + } |
| 16 | + canvas { |
| 17 | + border: 1px solid #000; |
| 18 | + } |
| 19 | + </style> |
| 20 | +</head> |
| 21 | +<body> |
| 22 | + <canvas id="canvas" width="800" height="300"></canvas> |
| 23 | + <script> |
| 24 | + const audioContext = new (window.AudioContext || window.webkitAudioContext)(); |
| 25 | + const canvas = document.getElementById('canvas'); |
| 26 | + const canvasCtx = canvas.getContext('2d'); |
| 27 | + let analyser; |
| 28 | + |
| 29 | + async function setupAudio() { |
| 30 | + try { |
| 31 | + const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); |
| 32 | + const source = audioContext.createMediaStreamSource(stream); |
| 33 | + analyser = audioContext.createAnalyser(); |
| 34 | + analyser.fftSize = 2048; |
| 35 | + source.connect(analyser); |
| 36 | + draw(); |
| 37 | + } catch (err) { |
| 38 | + console.error('Error accessing microphone:', err); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + function draw() { |
| 43 | + const bufferLength = analyser.frequencyBinCount; |
| 44 | + const dataArray = new Uint8Array(bufferLength); |
| 45 | + |
| 46 | + function drawSpectrum() { |
| 47 | + requestAnimationFrame(drawSpectrum); |
| 48 | + |
| 49 | + analyser.getByteFrequencyData(dataArray); |
| 50 | + |
| 51 | + canvasCtx.fillStyle = 'rgb(200, 200, 200)'; |
| 52 | + canvasCtx.fillRect(0, 0, canvas.width, canvas.height); |
| 53 | + |
| 54 | + const barWidth = (canvas.width / bufferLength) * 2.5; |
| 55 | + let x = 0; |
| 56 | + |
| 57 | + for (let i = 0; i < bufferLength; i++) { |
| 58 | + const barHeight = dataArray[i]; // Removed division by 2 |
| 59 | + |
| 60 | + canvasCtx.fillStyle = `rgb(${barHeight + 100}, 50, 50)`; |
| 61 | + canvasCtx.fillRect(x, canvas.height - barHeight, barWidth, barHeight); |
| 62 | + |
| 63 | + x += barWidth + 1; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + drawSpectrum(); |
| 68 | + } |
| 69 | + |
| 70 | + setupAudio(); |
| 71 | + </script> |
| 72 | +</body> |
| 73 | +</html> |
0 commit comments