TypeScript / JavaScript
After installing (npm install @warrenbuckley/audio-visualizer lit), import once to register the element globally:
import '@warrenbuckley/audio-visualizer';To get the typed class for casting and autocompletion, import AudioVisualizer:
import { AudioVisualizer, type VisualizerSize } from '@warrenbuckley/audio-visualizer';Full example
Section titled “Full example”import '@warrenbuckley/audio-visualizer';import type { AudioVisualizer } from '@warrenbuckley/audio-visualizer';
const viz = document.querySelector('audio-visualizer') as AudioVisualizer;const startBtn = document.getElementById('start') as HTMLButtonElement;const stopBtn = document.getElementById('stop') as HTMLButtonElement;const deviceSel = document.getElementById('devices') as HTMLSelectElement;
// Start with the default microphonestartBtn.addEventListener('click', async () => { try { startBtn.disabled = true; await viz.startMicrophone(); startBtn.textContent = 'Mic active';
// Labels only available after permission is granted const devices = await navigator.mediaDevices.enumerateDevices(); devices .filter(d => d.kind === 'audioinput') .forEach(mic => { const opt = document.createElement('option'); opt.value = mic.deviceId; opt.textContent = mic.label || 'Microphone'; deviceSel.appendChild(opt); }); deviceSel.disabled = false; } catch (err) { startBtn.disabled = false; console.error('Microphone error:', err); }});
// Switch devicedeviceSel.addEventListener('change', () => { viz.startMicrophone(deviceSel.value || undefined);});
// StopstopBtn.addEventListener('click', () => { viz.stopMicrophone(); startBtn.disabled = false; startBtn.textContent = 'Start microphone';});Checking active state
Section titled “Checking active state”if (viz.isActive) { console.log('Microphone is running');}Changing attributes programmatically
Section titled “Changing attributes programmatically”Attributes and their corresponding JS properties are reactive — changing either immediately updates the rendered output:
// Via attributeviz.setAttribute('size', 'lg');viz.setAttribute('bar-count', '7');
// Via propertyviz.size = 'lg';viz.barCount = 7;
// Via CSS custom propertyviz.style.setProperty('--audio-visualizer-color', '#ec4899');viz.style.setProperty('--audio-visualizer-transition', '60ms');