// Audio Context and Analyser let audioContext; let analyser; let microphone; let dataArray; let isListening = false; let animationId; let currentVisualizer = 'bars'; let threeDScene, threeDCamera, threeDRenderer, threeDParticles; // DOM Elements const startBtn = document.getElementById('startBtn'); const stopBtn = document.getElementById('stopBtn'); const visualizerType = document.getElementById('visualizerType'); const volumeLevel = document.getElementById('volumeLevel'); const frequencyData = document.getElementById('frequencyData'); const statusText = document.getElementById('statusText'); const canvas2d = document.getElementById('2dCanvas'); const ctx2d = canvas2d.getContext('2d'); const container3d = document.getElementById('3dContainer'); // Canvas setup canvas2d.width = canvas2d.offsetWidth; canvas2d.height = canvas2d.offsetHeight; // Event Listeners startBtn.addEventListener('click', startListening); stopBtn.addEventListener('click', stopListening); visualizerType.addEventListener('change', changeVisualizer); window.addEventListener('resize', () => { canvas2d.width = canvas2d.offsetWidth; canvas2d.height = canvas2d.offsetHeight; if (currentVisualizer.includes('3d') && threeDRenderer) { threeDCamera.aspect = container3d.offsetWidth / container3d.offsetHeight; threeDCamera.updateProjectionMatrix(); threeDRenderer.setSize(container3d.offsetWidth, container3d.offsetHeight); } }); // Audio Functions async function startListening() { try { // First check if we have permission const permissionStatus = await navigator.permissions.query({ name: 'microphone' }); if (permissionStatus.state === 'denied') { statusText.textContent = "Microphone access denied. Please check browser permissions."; statusText.className = "text-red-400"; return; } // Create audio context only after user interaction audioContext = new (window.AudioContext || window.webkitAudioContext)(); analyser = audioContext.createAnalyser(); analyser.fftSize = 256; // Explicitly request microphone with better error handling const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } }).catch(err => { console.error('Microphone access error:', err); statusText.textContent = `Error: ${err.message}`; statusText.className = "text-red-400"; throw err; }); microphone = audioContext.createMediaStreamSource(stream); microphone.connect(analyser); // Handle when stream ends (e.g., user revokes permission) stream.getAudioTracks()[0].onended = () => { statusText.textContent = "Microphone access was revoked"; statusText.className = "text-red-400"; stopListening(); }; dataArray = new Uint8Array(analyser.frequencyBinCount); isListening = true; startBtn.disabled = true; stopBtn.disabled = false; statusText.textContent = "Listening..."; statusText.className = "text-green-400"; animate(); } catch (error) { console.error('Error accessing microphone:', error); statusText.textContent = "Error accessing microphone"; statusText.className = "text-red-400"; } } function stopListening() { if (microphone) { try { microphone.disconnect(); if (microphone.mediaStream) { microphone.mediaStream.getTracks().forEach(track => { track.stop(); track.onended = null; // Clean up event listener }); } } catch (err) { console.error('Error stopping microphone:', err); } } if (audioContext) { audioContext.close(); } isListening = false; startBtn.disabled = false; stopBtn.disabled = true; statusText.textContent = "Microphone inactive"; statusText.className = "text-pink-400"; cancelAnimationFrame(animationId); // Clear canvas ctx2d.clearRect(0, 0, canvas2d.width, canvas2d.height); // Clear 3D scene if active if (threeDRenderer) { threeDRenderer.dispose(); if (threeDParticles) { container3d.removeChild(threeDRenderer.domElement); } } } function changeVisualizer() { currentVisualizer = visualizerType.value; if (currentVisualizer.includes('3d')) { canvas2d.classList.add('hidden'); container3d.classList.remove('hidden'); init3DVisualizer(); } else { if (threeDRenderer) { container3d.classList.add('hidden'); canvas2d.classList.remove('hidden'); } } } // Visualization Functions function animate() { if (!isListening) return; analyser.getByteFrequencyData(dataArray); switch (currentVisualizer) { case 'bars': drawBars(); break; case 'wave': drawWave(); break; case 'circle': drawCircle(); break; case '3d': update3DParticles(); break; case 'sphere': update3DSphere(); break; } // Update volume meter const volume = calculateVolume(dataArray); volumeLevel.style.width = `${volume * 100}%`; frequencyData.textContent = `Frequency bins: ${dataArray.length}`; animationId = requestAnimationFrame(animate); } function calculateVolume(array) { let sum = 0; for (let i = 0; i < array.length; i++) { sum += array[i]; } return sum / (array.length * 255); } function drawBars() { ctx2d.clearRect(0, 0, canvas2d.width, canvas2d.height); const barWidth = (canvas2d.width / dataArray.length) * 2.5; let x = 0; for (let i = 0; i < dataArray.length; i++) { const barHeight = (dataArray[i] / 255) * canvas2d.height; const hue = i / dataArray.length * 360; ctx2d.fillStyle = `hsl(${hue}, 100%, 50%)`; ctx2d.fillRect( x, canvas2d.height - barHeight, barWidth, barHeight ); x += barWidth + 1; } } function drawWave() { ctx2d.clearRect(0, 0, canvas2d.width, canvas2d.height); ctx2d.lineWidth = 2; ctx2d.strokeStyle = '#8b5cf6'; ctx2d.beginPath(); const sliceWidth = canvas2d.width / dataArray.length; let x = 0; for (let i = 0; i < dataArray.length; i++) { const v = dataArray[i] / 255; const y = v * canvas2d.height; if (i === 0) { ctx2d.moveTo(x, y); } else { ctx2d.lineTo(x, y); } x += sliceWidth; } ctx2d.lineTo(canvas2d.width, canvas2d.height / 2); ctx2d.stroke(); } function drawCircle() { ctx2d.clearRect(0, 0, canvas2d.width, canvas2d.height); const centerX = canvas2d.width / 2; const centerY = canvas2d.height / 2; const radius = Math.min(canvas2d.width, canvas2d.height) * 0.4; ctx2d.lineWidth = 2; for (let i = 0; i < dataArray.length; i++) { const angle = (i / dataArray.length) * Math.PI * 2; const value = dataArray[i] / 255; const pointRadius = value * radius * 0.3; const x = centerX + Math.cos(angle) * radius; const y = centerY + Math.sin(angle) * radius; const hue = i / dataArray.length * 360; ctx2d.fillStyle = `hsla(${hue}, 100%, 50%, 0.7)`; ctx2d.beginPath(); ctx2d.arc(x, y, pointRadius, 0, Math.PI * 2); ctx2d.fill(); // Connect points if (i > 0) { const prevAngle = ((i - 1) / dataArray.length) * Math.PI * 2; const prevX = centerX + Math.cos(prevAngle) * radius; const prevY = centerY + Math.sin(prevAngle) * radius; ctx2d.beginPath(); ctx2d.moveTo(prevX, prevY); ctx2d.lineTo(x, y); ctx2d.strokeStyle = `hsla(${hue}, 100%, 50%, 0.3)`; ctx2d.stroke(); } } } // 3D Visualizers function init3DVisualizer() { if (threeDRenderer) return; // Set up Three.js scene threeDScene = new THREE.Scene(); threeDCamera = new THREE.PerspectiveCamera( 75, container3d.offsetWidth / container3d.offsetHeight, 0.1, 1000 ); threeDCamera.position.z = 30; threeDRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); threeDRenderer.setSize(container3d.offsetWidth, container3d.offsetHeight); container3d.appendChild(threeDRenderer.domElement); if (currentVisualizer === '3d') { init3DParticles(); } else if (currentVisualizer === 'sphere') { init3DSphere(); } } function init3DParticles() { const particleCount = dataArray.length; const particles = new THREE.BufferGeometry(); const positions = new Float32Array(particleCount * 3); const colors = new Float32Array(particleCount * 3); const sizes = new Float32Array(particleCount); for (let i = 0; i < particleCount; i++) { const i3 = i * 3; // Position particles in a sphere const radius = 10; const theta = Math.random() * Math.PI * 2; const phi = Math.random() * Math.PI; positions[i3] = radius * Math.sin(phi) * Math.cos(theta); positions[i3 + 1] = radius * Math.sin(phi) * Math.sin(theta); positions[i3 + 2] = radius * Math.cos(phi); // Random colors colors[i3] = Math.random(); colors[i3 + 1] = Math.random(); colors[i3 + 2] = Math.random(); sizes[i] = 0.5; } particles.setAttribute('position', new THREE.BufferAttribute(positions, 3)); particles.setAttribute('color', new THREE.BufferAttribute(colors, 3)); particles.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); const particleMaterial = new THREE.PointsMaterial({ size: 0.5, vertexColors: true, transparent: true, opacity: 0.8, blending: THREE.AdditiveBlending }); threeDParticles = new THREE.Points(particles, particleMaterial); threeDScene.add(threeDParticles); // Add lights const ambientLight = new THREE.AmbientLight(0x404040); threeDScene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5); directionalLight.position.set(1, 1, 1); threeDScene.add(directionalLight); } function update3DParticles() { if (!threeDParticles) return; const positions = threeDParticles.geometry.attributes.position.array; const sizes = threeDParticles.geometry.attributes.size.array; for (let i = 0; i < dataArray.length; i++) { const i3 = i * 3; const value = dataArray[i] / 255; // Scale particles based on frequency data const scale = 1 + value * 5; sizes[i] = scale; // Add some movement positions[i3] += (Math.random() - 0.5) * 0.2; positions[i3 + 1] += (Math.random() - 0.5) * 0.2; positions[i3 + 2] += (Math.random() - 0.5) * 0.2; // Normalize positions to keep particles in a sphere const length = Math.sqrt( positions[i3] * positions[i3] + positions[i3 + 1] * positions[i3 + 1] + positions[i3 + 2] * positions[i3 + 2] ); if (length > 15) { positions[i3] *= 15 / length; positions[i3 + 1] *= 15 / length; positions[i3 + 2] *= 15 / length; } } threeDParticles.geometry.attributes.size.ne