@arraypress/waveform-player 1.14.0 → 1.16.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/index.d.ts CHANGED
@@ -76,9 +76,10 @@ export interface WaveformPlayerOptions {
76
76
  url?: string;
77
77
  /** Shorthand alias for {@link url} (`data-src`). The canonical name wins if both are set. */
78
78
  src?: string;
79
- /** Waveform height in pixels. @default 60 */
79
+ /** Waveform height in pixels. @default 64 */
80
80
  height?: number;
81
- /** Number of peak samples to extract when decoding. @default 200 */
81
+ /** Source peak resolution for live decode (ignored when `waveform` peaks are
82
+ * supplied); resampled to fit the visible bars. @default 1800 */
82
83
  samples?: number;
83
84
  /** `<audio>` preload hint. @default 'metadata' */
84
85
  preload?: AudioPreload;
@@ -96,7 +97,7 @@ export interface WaveformPlayerOptions {
96
97
  barWidth?: number;
97
98
  /** Gap between bars in pixels (style-dependent default). */
98
99
  barSpacing?: number;
99
- /** Rounded bar-cap radius in pixels (bars/mirror). `0` = square. @default 0 */
100
+ /** Rounded bar-cap radius in pixels (bars/mirror). `0` = square. @default 1 */
100
101
  barRadius?: number;
101
102
 
102
103
  // ── Colours ───────────────────────────────────────────────────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arraypress/waveform-player",
3
- "version": "1.14.0",
3
+ "version": "1.16.0",
4
4
  "description": "Lightweight, customizable audio player with waveform visualization",
5
5
  "type": "module",
6
6
  "types": "./index.d.ts",
@@ -268,6 +268,30 @@
268
268
  opacity: 1;
269
269
  }
270
270
 
271
+ /* Reveal the marker's label when the playhead reaches it (active marker). */
272
+ .waveform-marker.active .waveform-marker-tooltip {
273
+ opacity: 1;
274
+ }
275
+
276
+ /* Hover-time tooltip (showHoverTime) — follows the pointer over the waveform,
277
+ showing the time at that position. */
278
+ .waveform-hover-time {
279
+ position: absolute;
280
+ bottom: calc(100% + 4px);
281
+ transform: translateX(-50%);
282
+ background: rgba(0, 0, 0, 0.9);
283
+ color: #fff;
284
+ padding: 3px 7px;
285
+ border-radius: 4px;
286
+ font-size: 11px;
287
+ font-variant-numeric: tabular-nums;
288
+ white-space: nowrap;
289
+ pointer-events: none;
290
+ opacity: 0;
291
+ transition: opacity 0.15s;
292
+ z-index: 1000;
293
+ }
294
+
271
295
  /* Focus styles for accessibility */
272
296
  .waveform-btn:focus-visible {
273
297
  outline: 2px solid currentColor;
package/src/js/audio.js CHANGED
@@ -10,11 +10,12 @@ import {clamp} from './utils.js';
10
10
  * Extract peaks from a decoded audio buffer for waveform visualization.
11
11
  *
12
12
  * Divides the buffer into `samples` equal-width windows and, within each
13
- * window, finds the largest absolute amplitude. To keep large files fast the
14
- * inner loop strides through every 10th frame (`sampleStep`) rather than
15
- * inspecting every frame. Across multiple channels the per-window peaks are
16
- * merged by taking the loudest channel, then the whole array is normalized so
17
- * the maximum peak becomes 1 (a silent buffer is returned unscaled).
13
+ * window, finds the largest absolute amplitude by inspecting every frame (so
14
+ * transients are never missed and the shape is stable across sample counts —
15
+ * matching WaveformGen's offline output). Across multiple channels the
16
+ * per-window peaks are merged by taking the loudest channel, then the whole
17
+ * array is normalized so the maximum peak becomes 1 (a silent buffer is
18
+ * returned unscaled).
18
19
  *
19
20
  * @param {AudioBuffer} buffer - Decoded audio buffer to analyse.
20
21
  * @param {number} [samples=200] - Number of peak windows (output array length).
@@ -22,7 +23,6 @@ import {clamp} from './utils.js';
22
23
  */
23
24
  export function extractPeaks(buffer, samples = 200) {
24
25
  const sampleSize = buffer.length / samples;
25
- const sampleStep = ~~(sampleSize / 10) || 1;
26
26
  const channels = buffer.numberOfChannels;
27
27
  const peaks = [];
28
28
 
@@ -36,7 +36,12 @@ export function extractPeaks(buffer, samples = 200) {
36
36
  let min = 0;
37
37
  let max = 0;
38
38
 
39
- for (let j = start; j < end; j += sampleStep) {
39
+ // Scan EVERY frame in the window. Previously this stepped by
40
+ // sampleSize/10 (~10 samples/window) for speed, but that misses
41
+ // transients and makes the shape change with the sample count.
42
+ // decodeAudioData dominates the cost, so a full scan is worth it —
43
+ // and it now matches WaveformGen's offline output exactly.
44
+ for (let j = start; j < end; j++) {
40
45
  const value = chan[j];
41
46
  if (value > max) max = value;
42
47
  if (value < min) min = value;
package/src/js/core.js CHANGED
@@ -18,6 +18,15 @@ import {
18
18
 
19
19
  import {DEFAULT_OPTIONS, STYLE_DEFAULTS, getColorPreset, COLOR_PRESETS} from './themes.js';
20
20
 
21
+ /**
22
+ * Placeholder shown when an artwork URL fails to load (404 / broken) — a muted
23
+ * music-note tile, so a missing cover degrades gracefully instead of showing the
24
+ * browser's broken-image icon. Inline SVG data-URI (no font / network needed).
25
+ */
26
+ const ARTWORK_FALLBACK = 'data:image/svg+xml,' + encodeURIComponent(
27
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="#71717a" fill-opacity="0.15"/><g fill="none" stroke="#a1a1aa" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="17" r="2.2"/><circle cx="17" cy="15" r="2.2"/><path d="M10.2 17V7l9-1.6v9"/></g></svg>'
28
+ );
29
+
21
30
  // Keyboard seek steps (seconds) for the accessible slider.
22
31
  const SEEK_STEP_SECONDS = 5;
23
32
  const SEEK_PAGE_SECONDS = 10;
@@ -106,6 +115,7 @@ export class WaveformPlayer {
106
115
  this.ctx = null;
107
116
  this.waveformData = [];
108
117
  this.progress = 0;
118
+ this._activeMarkerIndex = -1;
109
119
  this.isPlaying = false;
110
120
  this.isLoading = false;
111
121
  this.hasError = false;
@@ -325,6 +335,12 @@ export class WaveformPlayer {
325
335
  this.titleEl = this.container.querySelector('.waveform-title');
326
336
  this.subtitleEl = this.container.querySelector('.waveform-subtitle');
327
337
  this.artworkEl = this.container.querySelector('.waveform-artwork');
338
+ if (this.artworkEl) {
339
+ // Fall back to the placeholder tile if the cover URL fails to load.
340
+ this.artworkEl.addEventListener('error', () => {
341
+ if (!this.artworkEl.src.startsWith('data:')) this.artworkEl.src = ARTWORK_FALLBACK;
342
+ });
343
+ }
328
344
  this.currentTimeEl = this.container.querySelector('.time-current');
329
345
  this.totalTimeEl = this.container.querySelector('.time-total');
330
346
  this.bpmEl = this.container.querySelector('.waveform-bpm');
@@ -717,6 +733,9 @@ export class WaveformPlayer {
717
733
  // so the controller can position its own audio element.
718
734
  this.canvas.addEventListener('click', (e) => this.handleCanvasClick(e));
719
735
 
736
+ // Hover-time tooltip over the waveform (when showHoverTime is on).
737
+ this.setupHoverTime();
738
+
720
739
  // Window resize - store handler for cleanup
721
740
  this.resizeHandler = debounce(() => this.resizeCanvas(), 100);
722
741
  window.addEventListener('resize', this.resizeHandler);
@@ -1031,6 +1050,8 @@ export class WaveformPlayer {
1031
1050
 
1032
1051
  // Always clear existing markers first
1033
1052
  this.markersContainer.innerHTML = '';
1053
+ // Re-sync the active marker on the next progress tick (the DOM was wiped).
1054
+ this._activeMarkerIndex = -1;
1034
1055
 
1035
1056
  if (!this.options.showMarkers || !this.options.markers?.length) return;
1036
1057
 
@@ -1090,6 +1111,62 @@ export class WaveformPlayer {
1090
1111
  markers.forEach((el, i) => el.classList.toggle('active', i === index));
1091
1112
  }
1092
1113
 
1114
+ /**
1115
+ * Highlight the marker the playhead has most recently passed — the rendered
1116
+ * marker with the greatest `time` ≤ the current time — and reveal its label.
1117
+ * Driven from the progress loop; a no-op when there are no markers. Reuses
1118
+ * {@link WaveformPlayer#setActiveMarker}, and only re-applies when the active
1119
+ * marker actually changes.
1120
+ * @private
1121
+ */
1122
+ updateActiveMarker() {
1123
+ if (!this.markersContainer) return;
1124
+ const els = this.markersContainer.querySelectorAll('.waveform-marker');
1125
+ if (!els.length) return;
1126
+ const dur = this.getSeekDuration();
1127
+ const t = dur ? this.progress * dur : 0;
1128
+ let active = -1;
1129
+ let best = -Infinity;
1130
+ els.forEach((el, i) => {
1131
+ const mt = parseFloat(el.getAttribute('data-time'));
1132
+ if (Number.isFinite(mt) && mt <= t + 0.05 && mt > best) {
1133
+ best = mt;
1134
+ active = i;
1135
+ }
1136
+ });
1137
+ if (active !== this._activeMarkerIndex) {
1138
+ this._activeMarkerIndex = active;
1139
+ this.setActiveMarker(active);
1140
+ }
1141
+ }
1142
+
1143
+ /**
1144
+ * Build a tooltip that follows the pointer over the waveform and shows the
1145
+ * time at that position. Enabled by the `showHoverTime` option; works in both
1146
+ * self and external modes (it only needs {@link WaveformPlayer#getSeekDuration}).
1147
+ * Uses the same pointer-X → percentage math as seeking.
1148
+ * @private
1149
+ */
1150
+ setupHoverTime() {
1151
+ if (!this.options.showHoverTime || !this.seekEl) return;
1152
+ const tip = document.createElement('div');
1153
+ tip.className = 'waveform-hover-time';
1154
+ tip.setAttribute('aria-hidden', 'true');
1155
+ this.seekEl.appendChild(tip);
1156
+ this.hoverTimeEl = tip;
1157
+
1158
+ this.seekEl.addEventListener('pointermove', (e) => {
1159
+ const dur = this.getSeekDuration();
1160
+ if (!dur) { tip.style.opacity = '0'; return; }
1161
+ const rect = this.canvas.getBoundingClientRect();
1162
+ const pct = clamp((e.clientX - rect.left) / rect.width);
1163
+ tip.textContent = formatTime(pct * dur);
1164
+ tip.style.left = (pct * 100) + '%';
1165
+ tip.style.opacity = '1';
1166
+ });
1167
+ this.seekEl.addEventListener('pointerleave', () => { tip.style.opacity = '0'; });
1168
+ }
1169
+
1093
1170
  // ============================================
1094
1171
  // Event Handlers
1095
1172
  // ============================================
@@ -1377,6 +1454,7 @@ export class WaveformPlayer {
1377
1454
  this.options.onTimeUpdate(this.audio.currentTime, this.audio.duration, this);
1378
1455
  }
1379
1456
 
1457
+ this.updateActiveMarker();
1380
1458
  this.updateSeekAccessibility();
1381
1459
  }
1382
1460
 
@@ -1639,6 +1717,7 @@ export class WaveformPlayer {
1639
1717
  this.totalTimeEl.dataset._extDur = String(duration);
1640
1718
  }
1641
1719
  this.drawWaveform?.();
1720
+ this.updateActiveMarker();
1642
1721
  this._emit('waveformplayer:timeupdate', {player: this, currentTime, duration, progress: this.progress, url: this.options.url});
1643
1722
  // Same (currentTime, duration, player) signature as self mode — the
1644
1723
  // arg order used to be swapped here, which made one shared handler
package/src/js/themes.js CHANGED
@@ -152,10 +152,12 @@ export const DEFAULT_OPTIONS = {
152
152
  // Core settings
153
153
  url: '',
154
154
  height: 64,
155
- // Source peak resolution. The drawer resamples these to fit
156
- // canvasWidth / (barWidth + barSpacing) bars, so this is fidelity headroom,
157
- // not the visible bar count.
158
- samples: 256,
155
+ // Source peak resolution for LIVE decode (ignored when peaks are supplied).
156
+ // The drawer resamples these to fit canvasWidth / (barWidth + barSpacing)
157
+ // bars, so this is fidelity headroom, not the visible bar count. 1800 (the
158
+ // SoundCloud/WaveformGen figure) keeps wide / high-DPI waveforms crisp; the
159
+ // every-frame scan means a higher value costs no extra extraction time.
160
+ samples: 1800,
159
161
  preload: 'metadata',
160
162
 
161
163
  // Audio mode — 'self' = player owns the <audio> element (default, current