@arraypress/waveform-player 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,286 +3,51 @@
3
3
  # WaveformPlayer
4
4
 
5
5
  **Zero-config audio waveforms for the web.**
6
- Add a `data-` attribute to a `<div>` — get a real, interactive waveform player. No build step, no dependencies, ~10KB.
6
+ Add a `data-` attribute to a `<div>` and get a real, interactive waveform player. No build step, no dependencies.
7
7
 
8
8
  [![npm](https://img.shields.io/npm/v/@arraypress/waveform-player?style=flat-square&labelColor=09090b&color=3f3f46)](https://www.npmjs.com/package/@arraypress/waveform-player)
9
- [![bundle size](https://img.shields.io/bundlephobia/minzip/@arraypress/waveform-player?style=flat-square&label=gzip&labelColor=09090b&color=3f3f46)](https://bundlephobia.com/package/@arraypress/waveform-player)
10
- [![downloads](https://img.shields.io/npm/dm/@arraypress/waveform-player?style=flat-square&labelColor=09090b&color=3f3f46)](https://www.npmjs.com/package/@arraypress/waveform-player)
11
- [![types](https://img.shields.io/npm/types/@arraypress/waveform-player?style=flat-square&labelColor=09090b&color=3f3f46)](./index.d.ts)
9
+ [![gzip](https://img.shields.io/bundlephobia/minzip/@arraypress/waveform-player?style=flat-square&label=gzip&labelColor=09090b&color=3f3f46)](https://bundlephobia.com/package/@arraypress/waveform-player)
12
10
  [![license](https://img.shields.io/npm/l/@arraypress/waveform-player?style=flat-square&labelColor=09090b&color=3f3f46)](./LICENSE)
13
11
 
14
- [Live demo](https://waveformplayer.com) · [Docs](https://waveformplayer.com/#docs) · [npm](https://www.npmjs.com/package/@arraypress/waveform-player)
15
-
16
- ![WaveformPlayer](./assets/og-image.svg)
12
+ **[Documentation](https://docs.waveformplayer.com/)** · [npm](https://www.npmjs.com/package/@arraypress/waveform-player)
17
13
 
18
14
  </div>
19
15
 
20
16
  ---
21
17
 
22
- ## Quick start
23
-
24
- No build tools. No initialization. Drop in two files and add a `<div>`.
25
-
26
- ```html
27
- <link rel="stylesheet" href="https://unpkg.com/@arraypress/waveform-player/dist/waveform-player.css">
28
- <script src="https://unpkg.com/@arraypress/waveform-player/dist/waveform-player.min.js"></script>
29
-
30
- <div data-waveform-player data-url="track.mp3" data-title="My Song"></div>
31
- ```
32
-
33
- It auto-initializes every `[data-waveform-player]` on the page when the DOM is ready. That's it.
34
-
35
18
  ## Install
36
19
 
37
20
  ```bash
38
21
  npm install @arraypress/waveform-player
39
22
  ```
40
23
 
41
- ```js
42
- import WaveformPlayer from '@arraypress/waveform-player';
43
- import '@arraypress/waveform-player/styles.css';
44
-
45
- const player = new WaveformPlayer('#player', { url: 'track.mp3' });
46
- ```
47
-
48
- Ships ESM + CommonJS + a standalone IIFE for `<script>` tags, with bundled TypeScript definitions.
49
-
50
- ## Why
51
-
52
- | | WaveformPlayer | WaveSurfer.js | Amplitude.js |
53
- | ------------------- | :------------: | :-----------: | :----------: |
54
- | Size (gzipped) | **~10KB** | 40KB+ | 35KB+ |
55
- | Zero-config (HTML) | ✓ | — | — |
56
- | Dependencies | None | None | None |
57
- | Real waveforms | ✓ | ✓ | — |
58
- | TypeScript types | ✓ | ✓ | — |
59
- | Keyboard + ARIA | ✓ | partial | — |
60
- | Media Session API | ✓ | — | — |
61
-
62
- ## Features
63
-
64
- - **Zero-config** — works from plain HTML via `data-` attributes; no JS required.
65
- - **6 visual styles** — bars, mirror, line, blocks, dots, seekbar — plus rounded caps and gradient fills.
66
- - **Real audio analysis** — decodes peaks with the Web Audio API, or uses pre-generated data.
67
- - **Accessible** — the waveform is a keyboard-operable ARIA slider out of the box.
68
- - **Framework-ready** — first-party [React](https://github.com/arraypress/waveform-player-react) and [Astro](https://github.com/arraypress/waveform-player-astro) wrappers; works anywhere otherwise.
69
- - **Batteries included** — chapter markers, BPM detection, Media Session, speed control, auto theme detection.
70
- - **Tiny** — ~10KB gzipped, zero dependencies, TypeScript types bundled.
71
-
72
- ## Visual styles
73
-
74
- Set with `data-style` (or the longer `data-waveform-style`), or the `style` / `waveformStyle` option.
75
-
76
- | Style | Look |
77
- | --------- | ----------------------------------- |
78
- | `mirror` | Symmetrical, SoundCloud-style (default) |
79
- | `bars` | Classic bottom-anchored bars |
80
- | `line` | Smooth oscilloscope line |
81
- | `blocks` | Segmented LED meter |
82
- | `dots` | Circular points |
83
- | `seekbar` | Minimal progress bar, no peaks |
84
-
85
- **Modern caps & gradients** (bundle-neutral):
86
-
87
- ```js
88
- new WaveformPlayer('#player', {
89
- url: 'track.mp3',
90
- waveformStyle: 'mirror',
91
- barRadius: 3, // rounded bar caps
92
- waveformColor: ['#fafafa', '#71717a'], // vertical gradient (array of stops)
93
- progressColor: ['#ffffff', '#a1a1aa'],
94
- });
95
- ```
96
-
97
- In zero-config markup, pass a gradient as a JSON array: `data-waveform-color='["#fafafa","#71717a"]'`.
98
-
99
- ## Usage
100
-
101
- ### HTML (zero JavaScript)
24
+ Load from a CDN and it auto-initializes every `[data-waveform-player]` on the page:
102
25
 
103
26
  ```html
104
- <div data-waveform-player
105
- data-url="track.mp3"
106
- data-title="My Song"
107
- data-artist="Artist Name"
108
- data-waveform-style="mirror"
109
- data-bar-radius="3"
110
- data-show-playback-speed="true"
111
- data-markers='[{"time": 30, "label": "Chorus"}]'>
112
- </div>
113
- ```
114
-
115
- ### Waveform only (custom UI)
27
+ <link rel="stylesheet" href="https://unpkg.com/@arraypress/waveform-player/dist/waveform-player.css">
28
+ <script src="https://unpkg.com/@arraypress/waveform-player/dist/waveform-player.min.js"></script>
116
29
 
117
- ```html
118
- <div data-waveform-player
119
- data-url="track.mp3"
120
- data-show-controls="false"
121
- data-show-info="false">
122
- </div>
30
+ <div data-waveform-player data-url="track.mp3" data-title="My Song" data-artist="The Artist"></div>
123
31
  ```
124
32
 
125
- ### JavaScript API
33
+ Or drive it from JavaScript:
126
34
 
127
35
  ```js
128
36
  import WaveformPlayer from '@arraypress/waveform-player';
129
37
 
130
- const player = new WaveformPlayer('#player', {
131
- url: 'track.mp3',
132
- waveformStyle: 'mirror',
133
- height: 80,
134
- markers: [
135
- { time: 30, label: 'Verse', color: '#4ade80' },
136
- { time: 60, label: 'Chorus', color: '#f59e0b' },
137
- ],
138
- });
139
- ```
140
-
141
- ## Options
142
-
143
- | Option | Type | Default | Description |
144
- | -------------------- | --------------------- | ----------- | ------------------------------------------------------- |
145
- | `url` | `string` | `''` | Audio file URL (alias: `src` / `data-src`) |
146
- | `waveformStyle` | `string` | `'mirror'` | `bars` · `mirror` · `line` · `blocks` · `dots` · `seekbar` |
147
- | `height` | `number` | `60` | Waveform height (px) |
148
- | `barWidth` | `number` | style-based | Bar width (px) |
149
- | `barSpacing` | `number` | style-based | Gap between bars (px) |
150
- | `barRadius` | `number` | `0` | Rounded bar-cap radius (px) — bars/mirror |
151
- | `waveformColor` | `string \| string[]` | preset | Unplayed colour; array = vertical gradient |
152
- | `progressColor` | `string \| string[]` | preset | Played colour; array = vertical gradient |
153
- | `colorPreset` | `'dark' \| 'light' \| null` | `null` | Force a theme, or `null` to auto-detect |
154
- | `samples` | `number` | `200` | Peak samples to extract |
155
- | `waveform` | `number[] \| string` | `null` | Pre-generated peaks (array, `.json` URL, or JSON) |
156
- | `audioMode` | `'self' \| 'external'`| `'self'` | Own the `<audio>`, or delegate (see below) |
157
- | `markers` | `WaveformMarker[]` | `[]` | Chapter markers |
158
- | `showControls` | `boolean` | `true` | Show the play/pause button |
159
- | `showInfo` | `boolean` | `true` | Show title/artist/time |
160
- | `showPlaybackSpeed` | `boolean` | `false` | Show the speed menu |
161
- | `showBPM` | `boolean` | `false` | Detect + display BPM |
162
- | `autoplay` | `boolean` | `false` | Play on load |
163
- | `enableMediaSession` | `boolean` | `true` | System media controls (self mode) |
164
- | `accessibleSeek` | `boolean` | `true` | Expose the waveform as a keyboard ARIA slider |
165
- | `seekLabel` | `string` | `null` | Accessible name for the slider (falls back to title) |
166
-
167
- Full option types ship in [`index.d.ts`](./index.d.ts).
168
-
169
- ## Accessibility
170
-
171
- By default the waveform is a keyboard-operable [ARIA slider](https://www.w3.org/WAI/ARIA/apg/patterns/slider/): `.waveform-container` gets `role="slider"`, joins the tab order, and reports `aria-valuemin`/`max`/`now` plus a readable `aria-valuetext` (e.g. `"0:30 of 2:00"`). When focused:
172
-
173
- | Key | Action |
174
- | -------------------------------------------- | ------------ |
175
- | <kbd>←</kbd> / <kbd>↓</kbd> · <kbd>→</kbd> / <kbd>↑</kbd> | Seek ∓5s |
176
- | <kbd>Page Down</kbd> / <kbd>Page Up</kbd> | Seek ∓10s |
177
- | <kbd>Home</kbd> / <kbd>End</kbd> | Start / end |
178
-
179
- Works in both audio modes, respects `prefers-reduced-motion`, and announces load errors to screen readers. Opt out with `accessibleSeek: false`; localize with `seekLabel`.
180
-
181
- ## API
182
-
183
- ```js
184
- player.play(); // returns the <audio>.play() promise in self mode
185
- player.pause();
186
- player.togglePlay();
187
-
188
- player.seekTo(30); // seconds
189
- player.seekToPercent(0.5);
190
- player.setVolume(0.8);
191
- player.setPlaybackRate(1.5);
192
-
193
- await player.loadTrack('next.mp3', 'Title', 'Artist', { artwork: 'cover.jpg' });
194
- player.destroy(); // removes all listeners + DOM
195
-
196
- // Statics
197
- WaveformPlayer.getInstance('id');
198
- WaveformPlayer.getAllInstances();
199
- WaveformPlayer.destroyAll();
200
- const peaks = await WaveformPlayer.generateWaveformData('track.mp3');
201
- const jsonUrl = WaveformPlayer.getPeaksUrl('track.mp3'); // -> 'track.json'
38
+ new WaveformPlayer('#player', { url: 'track.mp3', title: 'My Song', artist: 'The Artist' });
202
39
  ```
203
40
 
204
- ### Events
41
+ ## Documentation
205
42
 
206
- Lifecycle callbacks via options, or DOM events on the container (all bubble, `e.detail` is typed):
43
+ Every option, style, event and method is documented on the docs site.
207
44
 
208
- ```js
209
- new WaveformPlayer('#player', {
210
- url: 'track.mp3',
211
- onPlay: (player) => {},
212
- onPause: (player) => {},
213
- onEnd: (player) => {},
214
- onTimeUpdate: (currentTime, duration, player) => {},
215
- });
45
+ ### -> [docs.waveformplayer.com](https://docs.waveformplayer.com/)
216
46
 
217
- el.addEventListener('waveformplayer:timeupdate', (e) => {
218
- const { currentTime, duration, progress } = e.detail;
219
- });
220
- ```
221
-
222
- ## External audio mode
223
-
224
- Set `audioMode: 'external'` and the player becomes a visualization-only surface: play/pause/seek dispatch cancelable events, and you drive the canvas back with `setPlayingState()` / `setProgress()`. This is how [`@arraypress/waveform-bar`](https://github.com/arraypress/waveform-bar) turns many inline players into one persistent bar.
225
-
226
- ```js
227
- const player = new WaveformPlayer(el, { audioMode: 'external' });
47
+ [Options](https://docs.waveformplayer.com/player/options/) · [Waveform styles](https://docs.waveformplayer.com/player/waveform-styles/) · [Events](https://docs.waveformplayer.com/player/events/) · [Methods](https://docs.waveformplayer.com/player/methods/) · [Accessibility](https://docs.waveformplayer.com/player/accessibility/)
228
48
 
229
- el.addEventListener('waveformplayer:request-play', (e) => {
230
- audio.src = e.detail.url; // e.detail = { url, title, artist, artwork, id, player }
231
- audio.play();
232
- });
233
- audio.addEventListener('timeupdate', () => player.setProgress(audio.currentTime, audio.duration));
234
- audio.addEventListener('play', () => player.setPlayingState(true));
235
- audio.addEventListener('pause', () => player.setPlayingState(false));
236
- ```
237
-
238
- | Event | Detail |
239
- | ------------------------------ | --------------------------------------------------- |
240
- | `waveformplayer:request-play` | `{ url, title, artist, artwork, id, player }` |
241
- | `waveformplayer:request-pause` | Same shape |
242
- | `waveformplayer:request-seek` | Same shape + `{ percent: 0..1 }` |
243
-
244
- ## Frameworks
245
-
246
- | Environment | Package |
247
- | ----------- | ------- |
248
- | React | [`@arraypress/waveform-player-react`](https://github.com/arraypress/waveform-player-react) |
249
- | Astro | [`@arraypress/waveform-player-astro`](https://github.com/arraypress/waveform-player-astro) |
250
- | Vanilla / anything else | this package — `new WaveformPlayer(el, opts)` and `player.destroy()` on teardown |
251
-
252
- ## Ecosystem
253
-
254
- - **[WaveformBar](https://github.com/arraypress/waveform-bar)** — persistent bottom-bar player with queue, favorites, and cross-page session.
255
- - **[WaveformPlaylist](https://github.com/arraypress/waveform-playlist)** — zero-JS playlists and chapters.
256
- - **[WaveformGen](https://github.com/arraypress/waveform-gen)** — pre-generate peak JSON at build time.
257
- - **[WaveformTracker](https://github.com/arraypress/waveform-tracker)** — audio engagement analytics.
258
-
259
- ## Pre-generated waveforms
260
-
261
- Skip client-side decoding by storing peaks next to each file (`track.mp3` ↔ `track.json`):
262
-
263
- ```js
264
- new WaveformPlayer('#player', {
265
- url: track.audioUrl,
266
- waveform: WaveformPlayer.getPeaksUrl(track.audioUrl),
267
- });
268
- ```
269
-
270
- `getPeaksUrl()` swaps a known audio extension (`mp3`, `wav`, `ogg`, `flac`, `m4a`, `aac`) for `.json`, preserving query/hash, and returns `undefined` for anything else (so the player falls back to live decoding).
271
-
272
- ## Browser support
273
-
274
- Chrome/Edge 90+, Firefox 88+, Safari 14+, and modern mobile browsers. Rounded bar caps use `roundRect` where available (Safari 16+) and fall back to square bars elsewhere.
275
-
276
- ## Development
277
-
278
- ```bash
279
- npm install
280
- npm run dev # watch build
281
- npm test # vitest
282
- npm run build # all bundles
283
- npm run size # gzipped size
284
- ```
49
+ **Extensions:** [Bar](https://docs.waveformplayer.com/extensions/bar/) · [Playlist](https://docs.waveformplayer.com/extensions/playlist/) · [Tracker](https://docs.waveformplayer.com/extensions/tracker/) · [Gen](https://docs.waveformplayer.com/extensions/gen/) — **Frameworks:** [React](https://docs.waveformplayer.com/frameworks/react/) · [Vue](https://docs.waveformplayer.com/frameworks/vue/) · [Svelte](https://docs.waveformplayer.com/frameworks/svelte/) · [Astro](https://docs.waveformplayer.com/frameworks/astro/)
285
50
 
286
51
  ## License
287
52
 
288
- MIT © [ArrayPress](https://github.com/arraypress) · created by [David Sherlock](https://github.com/arraypress)
53
+ MIT © [ArrayPress](https://github.com/arraypress)
@@ -770,7 +770,12 @@ var DEFAULT_OPTIONS = {
770
770
  onPause: null,
771
771
  onEnd: null,
772
772
  onError: null,
773
- onTimeUpdate: null
773
+ onTimeUpdate: null,
774
+ // Optional queue navigation — when set, the player registers Media Session
775
+ // nexttrack/previoustrack handlers (lock-screen skip buttons). Called with
776
+ // the player instance; wired by waveform-bar / -playlist.
777
+ onNextTrack: null,
778
+ onPreviousTrack: null
774
779
  };
775
780
  var STYLE_DEFAULTS = {
776
781
  bars: { barWidth: 3, barSpacing: 1 },
@@ -1184,6 +1189,12 @@ var WaveformPlayer = class _WaveformPlayer {
1184
1189
  this.applySeekLabel();
1185
1190
  this.updateSeekAccessibility();
1186
1191
  this.seekEl.addEventListener("keydown", (e) => {
1192
+ if (e.key === " " || e.key === "Spacebar") {
1193
+ e.preventDefault();
1194
+ e.stopPropagation();
1195
+ this.togglePlay();
1196
+ return;
1197
+ }
1187
1198
  const duration = this.getSeekDuration();
1188
1199
  if (!duration) return;
1189
1200
  const current = this.getSeekCurrentTime();
@@ -1296,14 +1307,7 @@ var WaveformPlayer = class _WaveformPlayer {
1296
1307
  initMediaSession() {
1297
1308
  if (!("mediaSession" in navigator) || !this.options.enableMediaSession) return;
1298
1309
  if (!this.audio) return;
1299
- navigator.mediaSession.metadata = new MediaMetadata({
1300
- title: this.options.title || "Unknown Track",
1301
- artist: this.options.artist || "",
1302
- album: this.options.album || "",
1303
- artwork: this.options.artwork ? [
1304
- { src: this.options.artwork, sizes: "512x512", type: "image/jpeg" }
1305
- ] : []
1306
- });
1310
+ this._applyMediaMetadata();
1307
1311
  navigator.mediaSession.setActionHandler("play", () => this.play());
1308
1312
  navigator.mediaSession.setActionHandler("pause", () => this.pause());
1309
1313
  navigator.mediaSession.setActionHandler("seekbackward", () => {
@@ -1317,6 +1321,54 @@ var WaveformPlayer = class _WaveformPlayer {
1317
1321
  this.seekTo(details.seekTime);
1318
1322
  }
1319
1323
  });
1324
+ const onNext = this.options.onNextTrack, onPrev = this.options.onPreviousTrack;
1325
+ try {
1326
+ navigator.mediaSession.setActionHandler("nexttrack", typeof onNext === "function" ? () => onNext(this) : null);
1327
+ } catch (e) {
1328
+ }
1329
+ try {
1330
+ navigator.mediaSession.setActionHandler("previoustrack", typeof onPrev === "function" ? () => onPrev(this) : null);
1331
+ } catch (e) {
1332
+ }
1333
+ }
1334
+ /**
1335
+ * Publish the current track's Media Session metadata (lock-screen /
1336
+ * Now-Playing title, artist, album, artwork). Idempotent — safe to re-call.
1337
+ * @private
1338
+ */
1339
+ _applyMediaMetadata() {
1340
+ if (!("mediaSession" in navigator) || !this.options.enableMediaSession) return;
1341
+ navigator.mediaSession.metadata = new MediaMetadata({
1342
+ title: this.options.title || "Unknown Track",
1343
+ artist: this.options.artist || "",
1344
+ album: this.options.album || "",
1345
+ artwork: this.options.artwork ? [
1346
+ { src: this.options.artwork, sizes: "512x512", type: "image/jpeg" }
1347
+ ] : []
1348
+ });
1349
+ }
1350
+ /**
1351
+ * Sync Media Session playback state + scrubber position on play/pause. iOS
1352
+ * ignores metadata set before the media is active, so we re-assert it on
1353
+ * play — that's what fixes the blank lock-screen card on mobile.
1354
+ * @param {'playing'|'paused'} state
1355
+ * @private
1356
+ */
1357
+ _updateMediaSession(state) {
1358
+ if (!("mediaSession" in navigator) || !this.options.enableMediaSession || !this.audio) return;
1359
+ try {
1360
+ if (state === "playing") this._applyMediaMetadata();
1361
+ navigator.mediaSession.playbackState = state;
1362
+ const d = this.audio.duration;
1363
+ if (navigator.mediaSession.setPositionState && d && isFinite(d)) {
1364
+ navigator.mediaSession.setPositionState({
1365
+ duration: d,
1366
+ playbackRate: this.audio.playbackRate || 1,
1367
+ position: clamp(this.audio.currentTime, 0, d)
1368
+ });
1369
+ }
1370
+ } catch (e) {
1371
+ }
1320
1372
  }
1321
1373
  // ============================================
1322
1374
  // Event Binding
@@ -1380,6 +1432,7 @@ var WaveformPlayer = class _WaveformPlayer {
1380
1432
  const endDrag = (e) => {
1381
1433
  if (!this._dragging) return;
1382
1434
  this._dragging = false;
1435
+ this._suppressClick = true;
1383
1436
  try {
1384
1437
  this.canvas.releasePointerCapture(e.pointerId);
1385
1438
  } catch (err) {
@@ -1824,6 +1877,10 @@ var WaveformPlayer = class _WaveformPlayer {
1824
1877
  * @fires WaveformPlayer#waveformplayer:request-seek
1825
1878
  */
1826
1879
  handleCanvasClick(event) {
1880
+ if (this._suppressClick) {
1881
+ this._suppressClick = false;
1882
+ return;
1883
+ }
1827
1884
  this._seekFromPointer(event.clientX);
1828
1885
  }
1829
1886
  /**
@@ -1907,6 +1964,7 @@ var WaveformPlayer = class _WaveformPlayer {
1907
1964
  this.isPlaying = true;
1908
1965
  this.setPlayButtonState(true);
1909
1966
  this.startSmoothUpdate();
1967
+ this._updateMediaSession("playing");
1910
1968
  this._emit("waveformplayer:play", { player: this, url: this.options.url });
1911
1969
  if (this.options.onPlay) {
1912
1970
  this.options.onPlay(this);
@@ -1925,6 +1983,7 @@ var WaveformPlayer = class _WaveformPlayer {
1925
1983
  this.isPlaying = false;
1926
1984
  this.setPlayButtonState(false);
1927
1985
  this.stopSmoothUpdate();
1986
+ this._updateMediaSession("paused");
1928
1987
  this._emit("waveformplayer:pause", { player: this, url: this.options.url });
1929
1988
  if (this.options.onPause) {
1930
1989
  this.options.onPause(this);