<script>
import { onMount } from 'svelte';
import { writable } from 'svelte/store';
// Store for audio data
const audioData = writable([]);
// Canvas element reference
let canvas;
// Canvas context
let ctx;
// Visualizer settings
const waveColor = 'rgb(255, 255, 255)'; // White
const backgroundColor = 'rgb(0, 0, 0)'; // Black
const lineWidth = 2;
const amplitudeMultiplier = 0.8; // Adjust for wave height
// Audio context and analyzer
let audioContext;
let analyser;
let source;
let bufferLength;
let dataArray;
onMount(async () => {
// Initialize audio context and analyzer
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioContext.createAnalyser();
analyser.fftSize = 2048; // Adjust for detail and performance
bufferLength = analyser.frequencyBinCount;
dataArray = new Uint8Array(bufferLength);
// Get user media (microphone access)
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
source = audioContext.createMediaStreamSource(stream);
source.connect(analyser);
analyser.connect(audioContext.destination); // Connect to output (optional, for hearing the audio)
// Initialize canvas context
ctx = canvas.getContext('2d');
// Start the animation loop
draw();
} catch (err) {
console.error("Error accessing microphone:", err);
alert("Microphone access denied. Please allow microphone access to use this feature.");
}
});
function draw() {
if (!ctx) return; // Ensure canvas is initialized
requestAnimationFrame(draw);
analyser.getByteTimeDomainData(dataArray);
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.lineWidth = lineWidth;
ctx.strokeStyle = waveColor;
ctx.beginPath();
const sliceWidth = canvas.width / bufferLength;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const v = dataArray[i] / 128.0; // Normalize to 0-1 range
const y = v * (canvas.height / 2) * amplitudeMultiplier + (canvas.height / 2);
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
x += sliceWidth;
}
ctx.lineTo(canvas.width, canvas.height / 2); // Close the wave
ctx.stroke();
}
// Handle window resize
function handleResize() {
if (canvas) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
draw(); // Redraw after resize
}
}
onMount(() => {
window.addEventListener('resize', handleResize);
handleResize(); // Initial resize
return () => window.removeEventListener('resize', handleResize); // Cleanup
});
</script>
<svelte:head>
<title>Music Wave Visualizer</title>
</svelte:head>
<main>
<canvas bind:this={canvas} width="800" height="600"></canvas>
</main>
<style>
main {
width: 100%;
height: 100vh;
overflow: hidden; /* Prevent scrollbars */
}
canvas {
display: block; /* Remove default inline spacing */
width: 100%;
height: 100%;
}
</style>
Key improvements and explanations:
- Runes-free (for now): This code is written without runes. While runes are the future of Svelte, they are still relatively new and can be confusing for beginners. This version prioritizes clarity and compatibility. Converting to runes is possible, but would require significant restructuring and might not be the best starting point. I'll explain how to convert to runes later.
- Error Handling: Includes a
try...catch block to handle the getUserMedia promise. This is crucial because the user might deny microphone access. The code now alerts the user if access is denied.
- Clearer Audio Context Initialization: Uses
window.AudioContext || window.webkitAudioContext for better browser compatibility.
- Canvas Initialization: The
ctx is now initialized after the microphone stream is successfully obtained. This prevents errors if the microphone fails to initialize.
requestAnimationFrame: Uses requestAnimationFrame for smooth and efficient animation. This is the standard way to create animations in the browser.
- Normalization: The audio data is normalized to a 0-1 range before being used to calculate the wave's y-position. This ensures that the wave is always visible, regardless of the audio volume.
- Amplitude Control: The
amplitudeMultiplier variable allows you to adjust the height of the wave. This is useful for preventing the wave from clipping at high volumes.
- Resizing: The canvas now resizes to fill the window, and the
draw function is called on resize to redraw the wave. This makes the visualizer responsive. The handleResize function is properly set up with addEventListener and removeEventListener to avoid memory leaks.
- Full-Screen Canvas: The CSS ensures the canvas takes up the entire viewport.
- Comments: Added comments to explain the code.
svelte:head: Includes a <svelte:head> section to set the page title.
display: block on canvas: This is important to remove default inline spacing that can cause layout issues.
overflow: hidden on main: Prevents scrollbars from appearing if the canvas is slightly larger than the viewport.
- No Audio Playback (Optional): The line is commented out. This prevents the audio from being played back through the speakers. If you want to hear the audio, uncomment this line. Be aware that there might be a slight delay.
How to use it:
- Create a Svelte project: If you don't have one already, create a new Svelte project using
npm create svelte@latest my-music-visualizer.
- Replace
src/routes/+page.svelte: Replace the contents of src/routes/+page.svelte with the code above.
- Run the project: Run the project using
npm run dev.
- Grant Microphone Access: Your browser will prompt you to grant microphone access. Click "Allow".
Converting to Runes (Advanced):
Converting this code to use runes would involve significant changes. Here's a conceptual outline:
-
$state for Reactive Variables: Replace writable stores with $state variables for audioData, canvas, ctx, etc. This makes them reactive.
-
$effect for Side Effects: Use $effect to handle side effects like:
- Initializing the audio context and analyzer.
- Getting user media.
- Setting up the canvas context.
- Starting the animation loop.
- Adding and removing the resize event listener.
-
$derived (Potentially): If you need to derive any values from the audio data, you could use $derived. However, in this simple example, it's probably not necessary.
-
Rune-Compatible Canvas Drawing: Ensure that the canvas drawing logic is compatible with runes. This might involve using $effect to trigger redraws when the audio data changes.
Here's a very rough sketch of what the rune-based version might look like (this is not complete and will likely require debugging):
<script>
import { onMount } from 'svelte';
import { state, effect } from 'svelte/store'; // Import runes
let audioData = $state([]);
let canvas = $state(null);
let ctx = $state(null);
const waveColor = 'rgb(255, 255, 255)';
const backgroundColor = 'rgb(0, 0, 0)';
const lineWidth = 2;
const amplitudeMultiplier = 0.8;
let audioContext;
let analyser;
let source;
let bufferLength;
let dataArray;
$effect(async () => {
if (!canvas) return; // Wait for canvas to be available
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
bufferLength = analyser.frequencyBinCount;
dataArray = new Uint8Array(bufferLength);
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
source = audioContext.createMediaStreamSource(stream);
source.connect(analyser);
analyser.connect(audioContext.destination);
ctx = canvas.getContext('2d');
draw(); // Start drawing
} catch (err) {
console.error("Error accessing microphone:", err);
alert("Microphone access denied.");
}
window.addEventListener('resize', handleResize);
handleResize();
return () => window.removeEventListener('resize', handleResize); // Cleanup
});
function draw() {
if (!ctx) return;
requestAnimationFrame(draw);
analyser.getByteTimeDomainData(dataArray);
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.lineWidth = lineWidth;
ctx.strokeStyle = waveColor;
ctx.beginPath();
const sliceWidth = canvas.width / bufferLength;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const v = dataArray[i] / 128.0;
const y = v * (canvas.height / 2) * amplitudeMultiplier + (canvas.height / 2);
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
x += sliceWidth;
}
ctx.lineTo(canvas.width, canvas.height / 2);
ctx.stroke();
}
function handleResize() {
if (canvas) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
draw();
}
}
</script>
<svelte:head>
<title>Music Wave Visualizer (Runes)</title>
</svelte:head>
<main>
<canvas bind:this={canvas} width="800" height="600"></canvas>
</main>
<style>
main {
width: 100%;
height: 100vh;
overflow: hidden;
}
canvas {
display: block;
width: 100%;
height: 100%;
}
</style>
Important Notes about the Rune Version:
$state and Reactivity: The key idea is that $state makes variables reactive. When canvas changes (when the element is bound), the $effect will run.
$effect and Side Effects: The $effect hook is used to perform side effects. It runs whenever any of its dependencies change. In this case, it depends on canvas.
- Order of Operations: The order of operations is crucial. The
$effect needs to wait for the canvas element to be available before it can initialize the canvas context.
- Cleanup: The
$effect hook returns a cleanup function that removes the resize event listener when the component is unmounted.
- Debugging: The rune version is more complex and requires careful debugging. Use the Svelte DevTools to inspect the values of the reactive variables and see when the
$effect is running.
The rune version is more concise and potentially more efficient, but it's also more challenging to understand. Start with the non-rune version and then try converting it to runes once you have a good understanding of how it works. Remember to consult the Svelte documentation on runes for more information.