wavesurf
A production-ready React audio player built on WaveSurfer.js. Features waveform visualization, global state management, a persistent mini-player, and social sharing—everything you need for a music streaming experience.
Why wavesurf?
Building a good audio player is harder than it looks. You need:
- Global state so only one song plays at a time (like Spotify)
- Waveform visualization that's performant and interactive
- A persistent mini-player that stays visible while users browse
- Volume fade-in so playback doesn't blast at full volume
- Mobile responsiveness across all screen sizes
- Lazy loading so pages with many tracks don't lag
- Markers & regions for chapters, annotations and loops on the waveform
- A play queue with next/previous, auto-advance, repeat and shuffle
- OS media controls (lock screen, hardware keys) via the Media Session API
- Keyboard shortcuts and an accessible, keyboard-seekable waveform
wavesurf handles all of this out of the box, so you can focus on your actual product.
Installation
npm install wavesurf wavesurfer.js
Why wavesurfer.js is a peer dependency: You might already have it in your project, or want to control the version. Making it a peer dependency prevents duplicate bundles and version conflicts.
Quick Start
1. Add the Provider
Wrap your app (or the part that needs audio) with AudioPlayerProvider:
import { AudioPlayerProvider } from 'wavesurf';
export default function App() {
return (
<AudioPlayerProvider>
<YourApp />
</AudioPlayerProvider>
);
}
2. Add the Mini Player
Place MiniPlayer in your layout—it appears automatically when a song plays:
import { MiniPlayer } from 'wavesurf';
import 'wavesurf/styles.css';
export default function Layout({ children }) {
return (
<div>
{children}
<MiniPlayer />
</div>
);
}
3. Display Songs with WaveformPlayer
import { WaveformPlayer } from 'wavesurf';
function TrackList({ tracks }) {
return (
<div>
{tracks.map((track) => (
<WaveformPlayer
key={track.id}
song={{
id: track.id,
title: track.title,
artist: track.artist,
audioUrl: track.url,
duration: track.duration,
peaks: track.peaks, // Optional but recommended
}}
/>
))}
</div>
);
}
That's it. Click play on any track, and the mini-player appears. Click another track, and it seamlessly switches.
Architecture & Design Decisions
Global Audio Context
Problem: In a typical music app, you have multiple track listings, album pages, and a persistent player bar. Without global state, you'd have multiple <audio> elements fighting each other.
Solution: wavesurf uses React Context to maintain a single audio source. When you call play() from anywhere in your app, it:
- Pauses any currently playing audio
- Loads the new track
- Starts playback with a volume fade-in
- Notifies all
WaveformPlayer components to update their UI
// Any component can control playback
const { play, pause, currentSong, isPlaying } = useAudioPlayer();
Waveform Visualization (Why WaveSurfer.js?)
Problem: Audio waveforms require decoding audio data and rendering thousands of bars. Doing this poorly kills performance.
Solution: WaveSurfer.js is the industry standard for web audio visualization. It handles:
- Efficient canvas rendering
- Audio decoding
- Responsive resize handling
- Click-to-seek interactions
wavesurf wraps WaveSurfer.js with React lifecycle management, so you don't deal with manual cleanup or memory leaks.
Pre-computed Peaks (Performance)
Problem: Decoding audio to generate waveforms is slow—especially for longer tracks or pages with many songs. Users see loading spinners everywhere.
Solution: Generate peaks once (server-side), store them, and pass them to wavesurf:
<WaveformPlayer
song={{
id: '1',
title: 'My Song',
audioUrl: '/audio/song.mp3',
duration: 245,
peaks: [0.1, 0.3, 0.5, 0.8, ...], // Pre-computed!
}}
/>
When peaks are provided:
- No audio decoding needed — waveform renders instantly
- No network request for audio — until the user clicks play
- Pages load faster — even with 50+ tracks
How to Generate Peaks
Using audiowaveform (recommended):
# Install
brew install audiowaveform # macOS
apt install audiowaveform # Ubuntu
# Generate peaks
audiowaveform -i song.mp3 -o peaks.json --pixels-per-second 10 -b 8
Or server-side with FFmpeg/Node.js—compute once when uploading audio, store in your database.
Volume Fade-in (UX)
Problem: Clicking play and getting blasted with sudden audio is jarring. Users instinctively reach for the volume.
Solution: wavesurf fades volume from 0 to the user's set level over 3 seconds (configurable). This:
- Creates a professional, polished feel
- Prevents startling users
- Matches how streaming services behave
<AudioPlayerProvider config={{
fadeInEnabled: true, // default: true
fadeInDuration: 3000, // default: 3000ms
}}>
Volume Persistence (UX)
Problem: Users set their volume, navigate to another page, and it resets.
Solution: Volume is automatically saved to localStorage and restored on page load.
<AudioPlayerProvider config={{
persistVolume: true, // default: true
storageKey: 'myAppVolume', // default: 'audioPlayerVolume'
defaultVolume: 0.8, // default: 1
}}>
Lazy Loading (Performance)
Problem: A page with 20 tracks means 20 WaveSurfer instances initializing at once, causing jank.
Solution: wavesurf uses IntersectionObserver to only initialize waveforms when they scroll into view:
<WaveformPlayer
song={song}
lazyLoad={true} // default: true
/>
Tracks off-screen are just empty containers until needed.
Mini Player (UX Pattern)
Problem: Users want to browse your site while listening. A player embedded in the track list disappears when they navigate.
Solution: The MiniPlayer component is a fixed bar (bottom or top) that:
- Appears when playback starts
- Shows current track, progress, volume controls
- Has its own mini waveform for seeking
- Stays visible during navigation
- Can be closed by the user
<MiniPlayer
position="bottom" // or "top"
showVolume={true} // auto-hidden on mobile
showClose={true}
onClose={() => console.log('Player closed')}
/>
Components
AudioPlayerProvider
Wraps your app to provide global audio state.
<AudioPlayerProvider config={{
fadeInEnabled: true,
fadeInDuration: 3000,
persistVolume: true,
storageKey: 'audioPlayerVolume',
defaultVolume: 1,
defaultPlaybackRate: 1,
autoAdvance: true, // play the next queued song when one ends
mediaSession: true, // lock screen / hardware key controls
keyboardShortcuts: false, // global Space, arrows, M, N, P
seekStep: 5, // seconds per arrow key / media seek button
onPlay: (song) => analytics.track('play', song),
onPause: () => analytics.track('pause'),
onEnd: () => analytics.track('songEnded'),
onSongChange: (song, index) => {}, // queue moved to another song
onError: (error) => {}, // see "Errors & Loading"
onTimeUpdate: (time) => {},
}}>
{children}
</AudioPlayerProvider>
useAudioPlayer Hook
Access state and controls from any component:
const {
// State
currentSong, // Song | null
isPlaying, // boolean
currentTime, // number (seconds)
duration, // number (seconds)
volume, // number (0-1, user's saved volume)
displayVolume, // number (0-1, actual volume during fade)
isFadingIn, // boolean
isMuted, // boolean
playbackRate, // number (1 = normal)
isLoading, // boolean (loading or buffering)
error, // AudioPlayerError | null
queue, // Song[]
queueIndex, // number (-1 if the current song isn't in the queue)
repeat, // 'off' | 'all' | 'one'
shuffle, // boolean
hasNext, // boolean
hasPrevious, // boolean
// Actions
play, // (song: Song) => void
pause, // () => void
togglePlay, // () => void
seek, // (time: number) => void
setVolume, // (volume: number) => void
toggleMute, // () => void (keeps the volume setting)
setMuted, // (muted: boolean) => void
setPlaybackRate,// (rate: number) => void, 0.25-4, pitch preserved
stop, // () => void
clearError, // () => void
// Queue
setQueue, // (songs: Song[]) => void
playQueue, // (songs: Song[], startIndex?: number) => void
addToQueue, // (song: Song) => void
clearQueue, // () => void
next, // () => boolean
previous, // () => boolean
setRepeat, // (mode: 'off' | 'all' | 'one') => void
setShuffle, // (shuffle: boolean) => void
} = useAudioPlayer();
Queue
Hand the provider the list of songs and it takes care of what plays next. The usual pattern is to set the queue where the track list renders, so any WaveformPlayer play button continues into the rest of the list:
function TrackList({ tracks }) {
const { setQueue } = useAudioPlayer();
useEffect(() => {
setQueue(tracks);
}, [tracks, setQueue]);
return tracks.map((track) => <WaveformPlayer key={track.id} song={track} />);
}
setQueue never interrupts playback. If the current song is in the new queue, next/previous continue from its position. To start playing right away, use playQueue(tracks, startIndex).
What the queue does:
- Auto-advance. When a song ends the next one starts (no fade-in between tracks). Turn it off with
autoAdvance: false.
- Next / previous.
next() and previous() return false when there is nowhere to go. previous() restarts the current song if more than 3 seconds have played, like every other player.
- Repeat.
setRepeat('all') wraps around at the ends, setRepeat('one') replays the current song.
- Shuffle.
setShuffle(true) plays the rest of the queue in random order, each song once.
- Callbacks.
onSongChange(song, index) fires when the queue moves, whether by next(), previous(), a hardware key or auto-advance.
The MiniPlayer shows previous/next buttons whenever the queue has more than one song.
Media Session (lock screen & hardware keys)
When mediaSession is on (the default) the provider publishes the current song's title, artist, album and cover art to the OS, and wires play, pause, next, previous, seek and stop to the queue. That gives you lock-screen controls on phones, media keys on keyboards, and Bluetooth headset buttons for free. Browsers without the Media Session API are simply skipped.
Keyboard Shortcuts
Opt in with keyboardShortcuts: true. Shortcuts only work while a song is loaded and are ignored while typing in an input, textarea, select or contenteditable element.
| Key |
Action |
Space or K |
Play / pause |
Left / Right |
Seek back / forward by seekStep seconds (default 5) |
Up / Down |
Volume up / down 5% |
M |
Mute / unmute |
N / P |
Next / previous song |
Independently of this option, every WaveformPlayer waveform is a focusable slider: Tab to it and use Left/Right to seek 5 seconds, Home/End to jump to the start or end. Screen readers announce it as "Seek " with the current position.
Errors & Loading
Playback failures used to be silent. Now the provider exposes them:
interface AudioPlayerError {
code: 'blocked' | 'network' | 'decode' | 'unsupported' | 'aborted' | 'unknown';
message: string; // safe to show to users
song: Song | null; // the song that failed
}
error in useAudioPlayer() holds the latest error, cleared when a new song starts or by clearError().
onError(error) in the provider config fires for every error.
isLoading is true while the audio is loading or buffering.
'blocked' means the browser refused to autoplay. The fix is to start playback from a click, which WaveformPlayer and MiniPlayer already do.
MiniPlayer and WaveformPlayer show the message under the title or waveform. Pass showError={false} to render it yourself.
WaveformPlayer
Displays a track with waveform visualization: