Building a Real Audio Hover Preview with Zero Dependencies
说明与用途
使用 iTunes Search API 和 Web Audio API 实现了一个轻量级的悬停预览功能,能够在不使用任何框架或依赖的情况下即时播放 30 秒音频片段,并显示真实的均衡器。该方案兼容触摸设备、支持可访问性设置,并通过生成计数器防止竞态条件。
问题
Provide instant audio previews on artist cards without page loads, frameworks, or extra dependencies.
结果
A zero‑dependency, vanilla‑JS hover preview that plays music instantly, displays a real equalizer, handles race conditions, and respects accessibility settings.
工作流
- Fetch preview URLs from iTunes Search API and cache them on the card’s data attributes.
- Create an Audio element, AudioContext, and AnalyserNode to read real frequency data.
- Draw 8 equalizer bars from the analyser’s frequency bins using requestAnimationFrame.
- Implement a race‑condition guard with a generation counter to cancel stale callbacks.
- Apply CSS media queries for touch devices and prefers‑reduced‑motion to disable hover previews when appropriate.
- Add optional extras: document title swap, Media Session API, and cross‑origin handling for Apple’s CDN.
证据
Apple's iTunes Search API is a public endpoint that doesn't need authentication.
The preview URL gets cached on the card's data- attribute. First hover does the lookup. Every hover after that is instant.
The 8-bar equalizer isn't animated CSS pretending to be sound. It reads actual frequency data from the audio.
New hover bumps the counter. Every previous hover's callbacks check before touching the DOM. The orphaned callbacks just die silently.
Touch devices (hover: none, pointer: coarse): hover never fires. A tap on the photo toggles play/stop.
- 记录日期: 2026-10-07T18:40:50.350Z