diff --git a/src/app.html b/src/app.html
index 8123e99..bad2ffa 100644
--- a/src/app.html
+++ b/src/app.html
@@ -43,7 +43,7 @@
}
-
+
%sveltekit.body%
diff --git a/src/lib/components/audio-visualizations/BarVisualizer.svelte b/src/lib/components/audio-visualizations/BarVisualizer.svelte
new file mode 100644
index 0000000..a034c7e
--- /dev/null
+++ b/src/lib/components/audio-visualizations/BarVisualizer.svelte
@@ -0,0 +1,78 @@
+
+
+
diff --git a/src/lib/components/audio-visualizations/MicrophoneVisualizer.svelte b/src/lib/components/audio-visualizations/MicrophoneVisualizer.svelte
new file mode 100644
index 0000000..5e79330
--- /dev/null
+++ b/src/lib/components/audio-visualizations/MicrophoneVisualizer.svelte
@@ -0,0 +1,29 @@
+
+
+
diff --git a/src/lib/components/audio-visualizations/SpeakerVisualizer.svelte b/src/lib/components/audio-visualizations/SpeakerVisualizer.svelte
new file mode 100644
index 0000000..7983d40
--- /dev/null
+++ b/src/lib/components/audio-visualizations/SpeakerVisualizer.svelte
@@ -0,0 +1,38 @@
+
+
+
diff --git a/src/lib/components/audio-visualizations/analysis/audio_analysis.js b/src/lib/components/audio-visualizations/analysis/audio_analysis.js
new file mode 100644
index 0000000..4af34d5
--- /dev/null
+++ b/src/lib/components/audio-visualizations/analysis/audio_analysis.js
@@ -0,0 +1,203 @@
+import {
+ noteFrequencies,
+ noteFrequencyLabels,
+ voiceFrequencies,
+ voiceFrequencyLabels,
+} from './constants.js';
+
+/**
+ * Output of AudioAnalysis for the frequency domain of the audio
+ * @typedef {Object} AudioAnalysisOutputType
+ * @property {Float32Array} values Amplitude of this frequency between {0, 1} inclusive
+ * @property {number[]} frequencies Raw frequency bucket values
+ * @property {string[]} labels Labels for the frequency bucket values
+ */
+
+/**
+ * Analyzes audio for visual output
+ * @class
+ */
+export class AudioAnalysis {
+ /**
+ * Retrieves frequency domain data from an AnalyserNode adjusted to a decibel range
+ * returns human-readable formatting and labels
+ * @param {AnalyserNode} analyser
+ * @param {number} sampleRate
+ * @param {Float32Array} [fftResult]
+ * @param {"frequency"|"music"|"voice"} [analysisType]
+ * @param {number} [minDecibels] default -100
+ * @param {number} [maxDecibels] default -30
+ * @returns {AudioAnalysisOutputType}
+ */
+ static getFrequencies(
+ analyser,
+ sampleRate,
+ fftResult,
+ analysisType = 'frequency',
+ minDecibels = -100,
+ maxDecibels = -30,
+ ) {
+ if (!fftResult) {
+ fftResult = new Float32Array(analyser.frequencyBinCount);
+ analyser.getFloatFrequencyData(fftResult);
+ }
+ const nyquistFrequency = sampleRate / 2;
+ const frequencyStep = (1 / fftResult.length) * nyquistFrequency;
+ let outputValues;
+ let frequencies;
+ let labels;
+ if (analysisType === 'music' || analysisType === 'voice') {
+ const useFrequencies =
+ analysisType === 'voice' ? voiceFrequencies : noteFrequencies;
+ const aggregateOutput = Array(useFrequencies.length).fill(minDecibels);
+ for (let i = 0; i < fftResult.length; i++) {
+ const frequency = i * frequencyStep;
+ const amplitude = fftResult[i];
+ for (let n = useFrequencies.length - 1; n >= 0; n--) {
+ if (frequency > useFrequencies[n]) {
+ aggregateOutput[n] = Math.max(aggregateOutput[n], amplitude);
+ break;
+ }
+ }
+ }
+ outputValues = aggregateOutput;
+ frequencies =
+ analysisType === 'voice' ? voiceFrequencies : noteFrequencies;
+ labels =
+ analysisType === 'voice' ? voiceFrequencyLabels : noteFrequencyLabels;
+ } else {
+ outputValues = Array.from(fftResult);
+ frequencies = outputValues.map((_, i) => frequencyStep * i);
+ labels = frequencies.map((f) => `${f.toFixed(2)} Hz`);
+ }
+ // We normalize to {0, 1}
+ const normalizedOutput = outputValues.map((v) => {
+ return Math.max(
+ 0,
+ Math.min((v - minDecibels) / (maxDecibels - minDecibels), 1),
+ );
+ });
+ const values = new Float32Array(normalizedOutput);
+ return {
+ values,
+ frequencies,
+ labels,
+ };
+ }
+
+ /**
+ * Creates a new AudioAnalysis instance for an HTMLAudioElement
+ * @param {HTMLAudioElement} audioElement
+ * @param {AudioBuffer|null} [audioBuffer] If provided, will cache all frequency domain data from the buffer
+ * @returns {AudioAnalysis}
+ */
+ constructor(audioElement, audioBuffer = null) {
+ this.fftResults = [];
+ if (audioBuffer) {
+ /**
+ * Modified from
+ * https://stackoverflow.com/questions/75063715/using-the-web-audio-api-to-analyze-a-song-without-playing
+ *
+ * We do this to populate FFT values for the audio if provided an `audioBuffer`
+ * The reason to do this is that Safari fails when using `createMediaElementSource`
+ * This has a non-zero RAM cost so we only opt-in to run it on Safari, Chrome is better
+ */
+ const { length, sampleRate } = audioBuffer;
+ const offlineAudioContext = new OfflineAudioContext({
+ length,
+ sampleRate,
+ });
+ const source = offlineAudioContext.createBufferSource();
+ source.buffer = audioBuffer;
+ const analyser = offlineAudioContext.createAnalyser();
+ analyser.fftSize = 8192;
+ analyser.smoothingTimeConstant = 0.1;
+ source.connect(analyser);
+ // limit is :: 128 / sampleRate;
+ // but we just want 60fps - cuts ~1s from 6MB to 1MB of RAM
+ const renderQuantumInSeconds = 1 / 60;
+ const durationInSeconds = length / sampleRate;
+ const analyze = (index) => {
+ const suspendTime = renderQuantumInSeconds * index;
+ if (suspendTime < durationInSeconds) {
+ offlineAudioContext.suspend(suspendTime).then(() => {
+ const fftResult = new Float32Array(analyser.frequencyBinCount);
+ analyser.getFloatFrequencyData(fftResult);
+ this.fftResults.push(fftResult);
+ analyze(index + 1);
+ });
+ }
+ if (index === 1) {
+ offlineAudioContext.startRendering();
+ } else {
+ offlineAudioContext.resume();
+ }
+ };
+ source.start(0);
+ analyze(1);
+ this.audio = audioElement;
+ this.context = offlineAudioContext;
+ this.analyser = analyser;
+ this.sampleRate = sampleRate;
+ this.audioBuffer = audioBuffer;
+ } else {
+ const audioContext = new AudioContext();
+ const track = audioContext.createMediaElementSource(audioElement);
+ const analyser = audioContext.createAnalyser();
+ analyser.fftSize = 8192;
+ analyser.smoothingTimeConstant = 0.1;
+ track.connect(analyser);
+ analyser.connect(audioContext.destination);
+ this.audio = audioElement;
+ this.context = audioContext;
+ this.analyser = analyser;
+ this.sampleRate = this.context.sampleRate;
+ this.audioBuffer = null;
+ }
+ }
+
+ /**
+ * Gets the current frequency domain data from the playing audio track
+ * @param {"frequency"|"music"|"voice"} [analysisType]
+ * @param {number} [minDecibels] default -100
+ * @param {number} [maxDecibels] default -30
+ * @returns {AudioAnalysisOutputType}
+ */
+ getFrequencies(
+ analysisType = 'frequency',
+ minDecibels = -100,
+ maxDecibels = -30,
+ ) {
+ let fftResult = null;
+ if (this.audioBuffer && this.fftResults.length) {
+ const pct = this.audio.currentTime / this.audio.duration;
+ const index = Math.min(
+ (pct * this.fftResults.length) | 0,
+ this.fftResults.length - 1,
+ );
+ fftResult = this.fftResults[index];
+ }
+ return AudioAnalysis.getFrequencies(
+ this.analyser,
+ this.sampleRate,
+ fftResult,
+ analysisType,
+ minDecibels,
+ maxDecibels,
+ );
+ }
+
+ /**
+ * Resume the internal AudioContext if it was suspended due to the lack of
+ * user interaction when the AudioAnalysis was instantiated.
+ * @returns {Promise}
+ */
+ async resumeIfSuspended() {
+ if (this.context.state === 'suspended') {
+ await this.context.resume();
+ }
+ return true;
+ }
+}
+
+globalThis.AudioAnalysis = AudioAnalysis;
diff --git a/src/lib/components/audio-visualizations/analysis/constants.js b/src/lib/components/audio-visualizations/analysis/constants.js
new file mode 100644
index 0000000..f14da38
--- /dev/null
+++ b/src/lib/components/audio-visualizations/analysis/constants.js
@@ -0,0 +1,60 @@
+/**
+ * Constants for help with visualization
+ * Helps map frequency ranges from Fast Fourier Transform
+ * to human-interpretable ranges, notably music ranges and
+ * human vocal ranges.
+ */
+
+// Eighth octave frequencies
+const octave8Frequencies = [
+ 4186.01, 4434.92, 4698.63, 4978.03, 5274.04, 5587.65, 5919.91, 6271.93,
+ 6644.88, 7040.0, 7458.62, 7902.13,
+];
+
+// Labels for each of the above frequencies
+const octave8FrequencyLabels = [
+ 'C',
+ 'C#',
+ 'D',
+ 'D#',
+ 'E',
+ 'F',
+ 'F#',
+ 'G',
+ 'G#',
+ 'A',
+ 'A#',
+ 'B',
+];
+
+/**
+ * All note frequencies from 1st to 8th octave
+ * in format "A#8" (A#, 8th octave)
+ */
+export const noteFrequencies = [];
+export const noteFrequencyLabels = [];
+for (let i = 1; i <= 8; i++) {
+ for (let f = 0; f < octave8Frequencies.length; f++) {
+ const freq = octave8Frequencies[f];
+ noteFrequencies.push(freq / Math.pow(2, 8 - i));
+ noteFrequencyLabels.push(octave8FrequencyLabels[f] + i);
+ }
+}
+
+/**
+ * Subset of the note frequencies between 32 and 2000 Hz
+ * 6 octave range: C1 to B6
+ */
+const voiceFrequencyRange = [32.0, 2000.0];
+export const voiceFrequencies = noteFrequencies.filter((_, i) => {
+ return (
+ noteFrequencies[i] > voiceFrequencyRange[0] &&
+ noteFrequencies[i] < voiceFrequencyRange[1]
+ );
+});
+export const voiceFrequencyLabels = noteFrequencyLabels.filter((_, i) => {
+ return (
+ noteFrequencies[i] > voiceFrequencyRange[0] &&
+ noteFrequencies[i] < voiceFrequencyRange[1]
+ );
+});
diff --git a/src/lib/components/audio-visualizations/analysis/utils.ts b/src/lib/components/audio-visualizations/analysis/utils.ts
new file mode 100644
index 0000000..b19287e
--- /dev/null
+++ b/src/lib/components/audio-visualizations/analysis/utils.ts
@@ -0,0 +1,63 @@
+const dataMap = new WeakMap();
+
+/**
+ * Normalizes a Float32Array to Array(m): We use this to draw amplitudes on a graph
+ * If we're rendering the same audio data, then we'll often be using
+ * the same (data, m, downsamplePeaks) triplets so we give option to memoize
+ */
+export const normalizeArray = (
+ data: Float32Array,
+ m: number,
+ downsamplePeaks: boolean = false,
+ memoize: boolean = false
+) => {
+ let cache, mKey, dKey;
+ if (memoize) {
+ mKey = m.toString();
+ dKey = downsamplePeaks.toString();
+ cache = dataMap.has(data) ? dataMap.get(data) : {};
+ dataMap.set(data, cache);
+ cache[mKey] = cache[mKey] || {};
+ if (cache[mKey][dKey]) {
+ return cache[mKey][dKey];
+ }
+ }
+ const n = data.length;
+ const result = new Array(m);
+ if (m <= n) {
+ // Downsampling
+ result.fill(0);
+ const count = new Array(m).fill(0);
+ for (let i = 0; i < n; i++) {
+ const index = Math.floor(i * (m / n));
+ if (downsamplePeaks) {
+ // take highest result in the set
+ result[index] = Math.max(result[index], Math.abs(data[i]));
+ } else {
+ result[index] += Math.abs(data[i]);
+ }
+ count[index]++;
+ }
+ if (!downsamplePeaks) {
+ for (let i = 0; i < result.length; i++) {
+ result[i] = result[i] / count[i];
+ }
+ }
+ } else {
+ for (let i = 0; i < m; i++) {
+ const index = (i * (n - 1)) / (m - 1);
+ const low = Math.floor(index);
+ const high = Math.ceil(index);
+ const t = index - low;
+ if (high >= n) {
+ result[i] = data[n - 1];
+ } else {
+ result[i] = data[low] * (1 - t) + data[high] * t;
+ }
+ }
+ }
+ if (memoize) {
+ cache[mKey as string][dKey as string] = result;
+ }
+ return result;
+};
diff --git a/src/lib/components/audio-visualizations/index.ts b/src/lib/components/audio-visualizations/index.ts
new file mode 100644
index 0000000..c9efed8
--- /dev/null
+++ b/src/lib/components/audio-visualizations/index.ts
@@ -0,0 +1,7 @@
+export { default as BarVisualizer } from './BarVisualizer.svelte';
+export { default as MicrophoneVisualizer } from './MicrophoneVisualizer.svelte';
+export { default as SpeakerVisualizer } from './SpeakerVisualizer.svelte';
+
+export { normalizeArray } from './analysis/utils';
+
+export { AudioAnalysis } from './analysis/audio_analysis';
diff --git a/src/lib/components/button/Button.svelte b/src/lib/components/button/Button.svelte
index 0658f62..d78e180 100644
--- a/src/lib/components/button/Button.svelte
+++ b/src/lib/components/button/Button.svelte
@@ -5,7 +5,7 @@
import { cn } from '$lib/utils';
export const buttonVariants = tv({
- base: 'focus-visible:outline hover:cursor-pointer motion-save:focus-visible:transition-transform focus-visible:outline-2 outline-offset-2 inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-2xl active:scale-95 text-sm font-medium motion-save:transition-all disabled:pointer-events-none disabled:opacity-50 duration-300 active:duration-100 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
+ base: 'focus-visible:outline hover:cursor-pointer motion-safe:focus-visible:transition-transform focus-visible:outline-2 outline-offset-2 inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-2xl active:scale-95 text-sm font-medium motion-safe:transition-all disabled:pointer-events-none disabled:opacity-50 duration-300 active:duration-100 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
variants: {
variant: {
primary:
diff --git a/src/lib/components/modal/Modal.svelte b/src/lib/components/modal/Modal.svelte
index 9c48cd7..9a42777 100644
--- a/src/lib/components/modal/Modal.svelte
+++ b/src/lib/components/modal/Modal.svelte
@@ -65,14 +65,14 @@
diff --git a/src/lib/components/tooltip/tooltip-content.svelte b/src/lib/components/tooltip/tooltip-content.svelte
index 5220762..34aa97c 100644
--- a/src/lib/components/tooltip/tooltip-content.svelte
+++ b/src/lib/components/tooltip/tooltip-content.svelte
@@ -14,7 +14,7 @@
bind:ref
{sideOffset}
class={cn(
- 'border-base-200 bg-base-100 text-base-900 motion-save:animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-base-800 dark:bg-base-900 dark:text-base-50 z-50 overflow-hidden rounded-2xl border px-3 py-1.5 text-sm',
+ 'border-base-200 bg-base-100 text-base-900 motion-safe:animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-base-800 dark:bg-base-900 dark:text-base-50 z-50 overflow-hidden rounded-2xl border px-3 py-1.5 text-sm',
className
)}
{...restProps}
diff --git a/src/lib/preview/AudioVisualizerPreview.svelte b/src/lib/preview/AudioVisualizerPreview.svelte
new file mode 100644
index 0000000..4cb4c26
--- /dev/null
+++ b/src/lib/preview/AudioVisualizerPreview.svelte
@@ -0,0 +1,90 @@
+
+
+Audio Visualizers
+
+
+
+
+
+
+
+
+
diff --git a/src/routes/components/+layout.svelte b/src/routes/components/+layout.svelte
index e251ea3..ecc1778 100644
--- a/src/routes/components/+layout.svelte
+++ b/src/routes/components/+layout.svelte
@@ -52,7 +52,8 @@
{ label: 'Image Card', href: 'image-card' },
{ label: 'Post', href: 'post' },
{ label: 'Voxel Art', href: 'voxel-art' },
- { label: 'Following Pointer', href: 'following-pointer' }
+ { label: 'Following Pointer', href: 'following-pointer' },
+ { label: 'Audio Visualizer', href: 'audio-visualizer' }
];
// sort components by label
diff --git a/src/routes/components/+page.svelte b/src/routes/components/+page.svelte
index feedfb1..8bb69d5 100644
--- a/src/routes/components/+page.svelte
+++ b/src/routes/components/+page.svelte
@@ -37,7 +37,7 @@
import ImageCardPreview from '$lib/preview/ImageCardPreview.svelte';
import PostPreview from '$lib/preview/PostPreview.svelte';
import VoxelArtPreview from '$lib/preview/VoxelArtPreview.svelte';
- import FollowingPointerPreview from '$lib/preview/FollowingPointerPreview.svelte';
+ import AudioVisualizerPreview from '$lib/preview/AudioVisualizerPreview.svelte';
All Components
@@ -46,6 +46,9 @@
+
diff --git a/src/routes/components/audio-visualizer/+page.svelte b/src/routes/components/audio-visualizer/+page.svelte
new file mode 100644
index 0000000..d08da42
--- /dev/null
+++ b/src/routes/components/audio-visualizer/+page.svelte
@@ -0,0 +1,5 @@
+
+
+