@arraypress/waveform-player 1.27.0 → 1.28.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/src/js/core.js CHANGED
@@ -153,6 +153,10 @@ export class WaveformPlayer {
153
153
  this.hasError = false;
154
154
  this.updateTimer = null;
155
155
  this.resizeObserver = null;
156
+ // Load ticket: every load() takes the next one, and anything that
157
+ // resumes after an await checks it still holds the current one before
158
+ // touching state. See load().
159
+ this._loadId = 0;
156
160
 
157
161
  // All DOM/document listeners are registered with this signal so a
158
162
  // single abort() in destroy() tears every one of them down (the old
@@ -185,8 +189,10 @@ export class WaveformPlayer {
185
189
  throw error;
186
190
  }
187
191
 
188
- // Dispatch ready event after initialization
189
- setTimeout(() => {
192
+ // Dispatch ready event after initialization. Kept so destroy() can
193
+ // cancel it — a player torn down inside this window must not announce
194
+ // itself to listeners that already saw its destroy event.
195
+ this._readyTimer = setTimeout(() => {
190
196
  this._emit('waveformplayer:ready', {player: this, url: this.options.url});
191
197
  }, 100);
192
198
  }
@@ -247,10 +253,15 @@ export class WaveformPlayer {
247
253
 
248
254
  // Ensure proper sizing after DOM is ready
249
255
  requestAnimationFrame(() => {
256
+ // Destroyed before the first frame (a wrapper that mounts and
257
+ // unmounts in one tick): don't start a load for a dead player.
258
+ if (this.isDestroying) return;
250
259
  this.resizeCanvas();
251
260
 
252
- // Load audio if URL provided
253
- if (this.options.url) {
261
+ // Load audio if URL provided — unless the caller already started
262
+ // a load()/loadTrack() before this frame, which would otherwise
263
+ // be decoded twice and superseded by this one.
264
+ if (this.options.url && !this._loadId) {
254
265
  this.load(this.options.url).then(() => {
255
266
  if (this.options.autoplay) {
256
267
  this.play()?.catch(() => {});
@@ -630,8 +641,11 @@ export class WaveformPlayer {
630
641
  // WaveformBar) owns playback rate. Skip the audio init but
631
642
  // still bind the speed control UI in case the controller
632
643
  // wants to mirror rate changes via events later.
644
+ // defaultPlaybackRate too: the media load algorithm resets
645
+ // playbackRate to it on every src change, so setting playbackRate
646
+ // alone is silently undone by the first load().
633
647
  if (this.audio && this.options.playbackRate && this.options.playbackRate !== 1) {
634
- this.audio.playbackRate = this.options.playbackRate;
648
+ this.audio.playbackRate = this.audio.defaultPlaybackRate = this.options.playbackRate;
635
649
  }
636
650
 
637
651
  // Initialize speed control UI if enabled
@@ -969,6 +983,10 @@ export class WaveformPlayer {
969
983
  // Session handlers; ours would conflict with its.
970
984
  if (!this.audio) return;
971
985
 
986
+ // The session is one global object; remember whose it is, so a
987
+ // paused player's seek can't move another player's lock-screen
988
+ // scrubber (see _updatePositionState).
989
+ WaveformPlayer._sessionOwner = this;
972
990
  this._applyMediaMetadata();
973
991
 
974
992
  // Set up action handlers
@@ -1026,14 +1044,26 @@ export class WaveformPlayer {
1026
1044
  // drive the player you're actually listening to, not the last one loaded.
1027
1045
  if (state === 'playing') this.initMediaSession();
1028
1046
  navigator.mediaSession.playbackState = state;
1029
- const d = this.audio.duration;
1030
- if (navigator.mediaSession.setPositionState && d && isFinite(d)) {
1031
- navigator.mediaSession.setPositionState({
1032
- duration: d,
1033
- playbackRate: this.audio.playbackRate || 1,
1034
- position: clamp(this.audio.currentTime, 0, d),
1035
- });
1036
- }
1047
+ this._updatePositionState();
1048
+ } catch (e) { /* Media Session is best-effort */ }
1049
+ }
1050
+
1051
+ /**
1052
+ * Publish duration, rate and position to the lock-screen scrubber. Runs
1053
+ * on play/pause and on the element's `seeked` / `ratechange`, so the
1054
+ * scrubber doesn't drift after a seek or a speed change until the next
1055
+ * play/pause. Only the player that owns the (global) session writes it.
1056
+ * @private
1057
+ */
1058
+ _updatePositionState() {
1059
+ const d = this.audio?.duration;
1060
+ if (WaveformPlayer._sessionOwner !== this || !navigator.mediaSession?.setPositionState || !(d && isFinite(d))) return;
1061
+ try {
1062
+ navigator.mediaSession.setPositionState({
1063
+ duration: d,
1064
+ playbackRate: this.audio.playbackRate || 1,
1065
+ position: clamp(this.audio.currentTime, 0, d),
1066
+ });
1037
1067
  } catch (e) { /* Media Session is best-effort */ }
1038
1068
  }
1039
1069
 
@@ -1068,6 +1098,18 @@ export class WaveformPlayer {
1068
1098
  this.audio.addEventListener('pause', () => this.onPause());
1069
1099
  this.audio.addEventListener('ended', () => this.onEnded());
1070
1100
  this.audio.addEventListener('error', (e) => this.onError(e));
1101
+ // Progress is normally driven by the rAF loop (smooth canvas), but
1102
+ // browsers stop animation frames in background tabs while the
1103
+ // audio keeps playing — and with them every timeupdate event and
1104
+ // onTimeUpdate call, which is what analytics (waveform-tracker)
1105
+ // count listening time from. The native event (~4Hz, still fired
1106
+ // in the background) takes over only once the loop has gone quiet,
1107
+ // so a foreground tab doesn't emit twice.
1108
+ this.audio.addEventListener('seeked', () => this._updatePositionState());
1109
+ this.audio.addEventListener('ratechange', () => this._updatePositionState());
1110
+ this.audio.addEventListener('timeupdate', () => {
1111
+ if (this.isPlaying && Date.now() - this._frameAt > 500) this.updateProgress();
1112
+ });
1071
1113
  }
1072
1114
 
1073
1115
  // Canvas interactions — click + drag to seek. pointerdown starts a
@@ -1179,29 +1221,54 @@ export class WaveformPlayer {
1179
1221
  * accessible name are written *before* the metadata wait, as are peaks
1180
1222
  * supplied via the `waveform` option — none of them need anything from the
1181
1223
  * audio element, and behind the wait they blink in on a slow origin.
1182
- * Without inline peaks the waveform is decoded from the audio instead; a
1183
- * decode failure falls back to a placeholder. The `onLoad` callback fires
1184
- * on success.
1224
+ * Without inline peaks — or when a `.json` peaks sidecar can't be fetched —
1225
+ * the waveform is decoded from the audio instead; a decode failure falls
1226
+ * back to a placeholder. The `onLoad` callback fires on success.
1227
+ *
1228
+ * Every call supersedes the previous one: a load that is overtaken while
1229
+ * it awaits (metadata, a sidecar fetch, the decode) stops there without
1230
+ * touching the player, so a slow first track can't land its peaks, BPM,
1231
+ * error or loading state on the track that replaced it.
1232
+ *
1233
+ * Loading a *different* URL also resets what the previous track left
1234
+ * behind (see {@link WaveformPlayer#_resetTrack}); reloading the same URL
1235
+ * — e.g. a retry after an error — keeps the drawn waveform. Either way the
1236
+ * error state is cleared, so a retry re-enables the player.
1185
1237
  * @param {string} url - Audio URL.
1186
1238
  * @returns {Promise<void>} Resolves once loading settles (errors are caught
1187
1239
  * internally and surfaced through {@link WaveformPlayer#onError}).
1188
1240
  */
1189
1241
  async load(url) {
1242
+ const id = ++this._loadId;
1243
+ // Held locally: destroy() nulls this.audio while the metadata wait
1244
+ // below is still pending, and its handlers must still be able to
1245
+ // unhook themselves and settle the promise.
1246
+ const audio = this.audio;
1190
1247
  try {
1248
+ if (url !== this.options.url) this._resetTrack();
1191
1249
  this.setLoading(true);
1192
1250
  this.progress = 0;
1193
- this.hasError = false;
1251
+ this._setError(false);
1194
1252
  this.container.classList.remove('waveform-is-placeholder');
1253
+ // A detected tempo describes the audio that was decoded, not the
1254
+ // one being loaded. A caller's `bpm` option still shows at once.
1255
+ this.detectedBPM = null;
1256
+ this.updateBPMDisplay();
1257
+
1258
+ // Record the URL first so every event emitted from here on (and
1259
+ // the extensions that read options.url, e.g. waveform-tracker)
1260
+ // reports the track actually loaded, even if the load fails.
1261
+ // loadTrack() already sets it; a direct load(url) didn't. See #30.
1262
+ this.options.url = url;
1195
1263
 
1196
1264
  // Caller-supplied peaks describe the file, not the element's
1197
1265
  // playback state, so draw them up front rather than behind the
1198
1266
  // metadata wait below. On a slow (or non-Range-capable) audio
1199
1267
  // origin that wait is seconds long, and the canvas used to sit
1200
- // blank for all of it. See issue #23.
1201
- const hasInlinePeaks = !!this.options.waveform;
1202
- if (hasInlinePeaks) {
1203
- this.setWaveformData(this.options.waveform);
1204
- }
1268
+ // blank for all of it. See issue #23. A `.json` sidecar comes back
1269
+ // as a promise, fetched in parallel with the metadata wait.
1270
+ const inlinePeaks = this.options.waveform;
1271
+ const sidecar = inlinePeaks ? this.setWaveformData(inlinePeaks) : null;
1205
1272
 
1206
1273
  // Same reasoning as the peaks above: the title comes from the
1207
1274
  // `title` option or the URL, so it needs nothing from the audio
@@ -1220,9 +1287,9 @@ export class WaveformPlayer {
1220
1287
  // waveform peaks so the canvas can render the visualization.
1221
1288
  // Duration / current time come from the external controller
1222
1289
  // via setProgress().
1223
- if (this.audio) {
1290
+ if (audio) {
1224
1291
  // Set audio source
1225
- this.audio.src = url;
1292
+ audio.src = url;
1226
1293
 
1227
1294
  // preload="none" tells the browser to fetch nothing until
1228
1295
  // play(), so `loadedmetadata` will never arrive and awaiting
@@ -1231,30 +1298,32 @@ export class WaveformPlayer {
1231
1298
  // wait; the bindEvents() `loadedmetadata` listener still
1232
1299
  // fires whenever metadata does land, and onMetadataLoaded()
1233
1300
  // fills in duration + markers then.
1234
- if (this.audio.preload !== 'none') {
1301
+ if (audio.preload !== 'none') {
1235
1302
  // Wait for metadata to load
1236
1303
  await new Promise((resolve, reject) => {
1237
- const metadataHandler = () => {
1238
- this.audio.removeEventListener('loadedmetadata', metadataHandler);
1239
- this.audio.removeEventListener('error', errorHandler);
1240
- resolve();
1241
- };
1242
- const errorHandler = (e) => {
1243
- this.audio.removeEventListener('loadedmetadata', metadataHandler);
1244
- this.audio.removeEventListener('error', errorHandler);
1245
- reject(e);
1304
+ const settle = (fn) => (e) => {
1305
+ audio.removeEventListener('loadedmetadata', metadataHandler);
1306
+ audio.removeEventListener('error', errorHandler);
1307
+ fn(e);
1246
1308
  };
1247
- this.audio.addEventListener('loadedmetadata', metadataHandler);
1248
- this.audio.addEventListener('error', errorHandler);
1309
+ const metadataHandler = settle(resolve);
1310
+ const errorHandler = settle(reject);
1311
+ audio.addEventListener('loadedmetadata', metadataHandler);
1312
+ audio.addEventListener('error', errorHandler);
1249
1313
  });
1250
1314
  }
1251
1315
  }
1252
1316
 
1253
- // Peaks were drawn above; only the decode path is left.
1254
- if (!hasInlinePeaks) {
1255
- // Generate waveform
1317
+ // `false` = the sidecar couldn't be used; `undefined` = inline
1318
+ // peaks (already drawn) or none at all.
1319
+ const sidecarOk = await sidecar;
1320
+ if (id !== this._loadId) return;
1321
+
1322
+ // No usable caller-supplied peaks: decode them from the audio.
1323
+ if (!inlinePeaks || sidecarOk === false) {
1256
1324
  try {
1257
1325
  const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
1326
+ if (id !== this._loadId) return;
1258
1327
  this.waveformData = result.peaks;
1259
1328
 
1260
1329
  // Store BPM if detected
@@ -1263,6 +1332,7 @@ export class WaveformPlayer {
1263
1332
  this.updateBPMDisplay();
1264
1333
  }
1265
1334
  } catch (error) {
1335
+ if (id !== this._loadId) return;
1266
1336
  console.warn('[WaveformPlayer] Using placeholder waveform:', error);
1267
1337
  this.waveformData = generatePlaceholderWaveform(this.options.samples);
1268
1338
  this.container.classList.add('waveform-is-placeholder');
@@ -1278,12 +1348,52 @@ export class WaveformPlayer {
1278
1348
  }
1279
1349
  } catch (error) {
1280
1350
  // onError() is the single funnel for surfacing + logging errors.
1281
- this.onError(error);
1351
+ // A self-mode media error reaches it twice — the bindEvents()
1352
+ // `error` listener runs first, then this rejection — so one
1353
+ // failure must not report twice. A superseded load's failure
1354
+ // belongs to a track nobody is waiting for.
1355
+ if (id === this._loadId && !this.hasError) this.onError(error);
1282
1356
  } finally {
1283
- this.setLoading(false);
1357
+ // Only the current load owns the loading state; a superseded one
1358
+ // finishing must not clear it while its successor is still busy.
1359
+ if (id === this._loadId) this.setLoading(false);
1284
1360
  }
1285
1361
  }
1286
1362
 
1363
+ /**
1364
+ * Forget everything the previous track left on the player: its peaks,
1365
+ * progress, duration (external mode), time readout and marker buttons.
1366
+ * Shared by {@link WaveformPlayer#loadTrack} and a {@link WaveformPlayer#load}
1367
+ * of a different URL, so neither path can show the old track's `1:30` or
1368
+ * place the new track's markers against the old duration. Per-track
1369
+ * *options* are reset by `loadTrack()`, which is the path that receives them.
1370
+ * @private
1371
+ */
1372
+ _resetTrack() {
1373
+ this.progress = 0;
1374
+ this.waveformData = [];
1375
+ this._extDuration = 0;
1376
+ this._extEnded = false;
1377
+ if (this.currentTimeEl) this.currentTimeEl.textContent = '0:00';
1378
+ if (this.totalTimeEl) this.totalTimeEl.textContent = '0:00';
1379
+ if (this.markersContainer) this.markersContainer.innerHTML = '';
1380
+ }
1381
+
1382
+ /**
1383
+ * Show or clear the error state: the overlay, the dimmed canvas and the
1384
+ * disabled play button. The one place both {@link WaveformPlayer#onError}
1385
+ * and a fresh {@link WaveformPlayer#load} flip it, so a retry can't leave
1386
+ * half of it behind.
1387
+ * @param {boolean} on - True to enter the error state, false to clear it.
1388
+ * @private
1389
+ */
1390
+ _setError(on) {
1391
+ this.hasError = on;
1392
+ if (this.errorEl) this.errorEl.style.display = on ? 'flex' : 'none';
1393
+ if (this.canvas) this.canvas.style.opacity = on ? '0.2' : '1';
1394
+ if (this.playBtn) this.playBtn.disabled = on;
1395
+ }
1396
+
1287
1397
  /**
1288
1398
  * Swap the player to a new track at runtime.
1289
1399
  *
@@ -1291,14 +1401,22 @@ export class WaveformPlayer {
1291
1401
  * clears error/marker/progress state, merges the new metadata into
1292
1402
  * `this.options`, updates the artist/artwork DOM, then calls
1293
1403
  * {@link WaveformPlayer#load}. Auto-plays the new track unless
1294
- * `options.autoplay === false`.
1404
+ * `options.autoplay === false` — and only if no later `loadTrack()` /
1405
+ * `load()` has superseded this one by the time it finishes loading.
1406
+ *
1407
+ * Per-track options the caller doesn't repeat are reset rather than
1408
+ * inherited from the previous track: `markers`, `waveform`, `bpm` and
1409
+ * `album`.
1295
1410
  * @param {string} url - Audio URL.
1296
1411
  * @param {string|null} [title=null] - Track title; keeps the existing
1297
- * title when null.
1412
+ * title when null. (Deliberate: a controller that only swaps the
1413
+ * audio keeps the label it set. Pass `''` to derive the title from the
1414
+ * URL instead.)
1298
1415
  * @param {string|null} [artist=null] - Track artist; pass `''` to hide
1299
1416
  * the artist row, or null to keep the existing one.
1300
1417
  * @param {Object} [options={}] - Additional options to merge (e.g.
1301
- * `preload`, `artwork`, `artworkAlt`, `markers`, `autoplay`).
1418
+ * `preload`, `artwork`, `artworkAlt`, `markers`, `bpm`, `album`,
1419
+ * `autoplay`).
1302
1420
  * @returns {Promise<void>}
1303
1421
  */
1304
1422
  async loadTrack(url, title = null, artist = null, options = {}) {
@@ -1316,21 +1434,9 @@ export class WaveformPlayer {
1316
1434
  this.audio.load();
1317
1435
  }
1318
1436
 
1319
- // Clear any errors
1320
- this.hasError = false;
1321
- if (this.errorEl) {
1322
- this.errorEl.style.display = 'none';
1323
- }
1324
- if (this.canvas) {
1325
- this.canvas.style.opacity = '1';
1326
- }
1327
- if (this.playBtn) {
1328
- this.playBtn.disabled = false;
1329
- }
1330
-
1331
- // Reset state
1332
- this.progress = 0;
1333
- this.waveformData = [];
1437
+ // Peaks, progress, duration, time readout, markers. The error state
1438
+ // is cleared by load() itself, so a plain load() retry gets it too.
1439
+ this._resetTrack();
1334
1440
 
1335
1441
  // Update options (including preload if specified). Normalized on the
1336
1442
  // same terms as the constructor — loadTrack takes a fresh, caller-
@@ -1350,6 +1456,13 @@ export class WaveformPlayer {
1350
1456
  this.options.artworkAlt = this.options.artwork ? DEFAULT_OPTIONS.artworkAlt : '';
1351
1457
  }
1352
1458
 
1459
+ // `bpm` and `album` describe one track. mergeOptions() skips null
1460
+ // sources, so without this the previous track's tempo badge and
1461
+ // lock-screen album would carry over to every track after it.
1462
+ for (const key of ['bpm', 'album']) {
1463
+ if (options[key] == null) this.options[key] = DEFAULT_OPTIONS[key];
1464
+ }
1465
+
1353
1466
  // Apply preload setting if it was changed. The caller's value decides
1354
1467
  // WHETHER to apply; the normalized one decides WHAT to apply, so an
1355
1468
  // unsupported value can't reach the media element.
@@ -1388,12 +1501,17 @@ export class WaveformPlayer {
1388
1501
  // waveform (audio changes, visualization doesn't).
1389
1502
  this.options.waveform = options.waveform || null;
1390
1503
 
1391
- // Load the new track
1392
- await this.load(url);
1504
+ // Load the new track. load() takes its ticket synchronously, so this
1505
+ // is the id to compare against once it settles.
1506
+ const loading = this.load(url);
1507
+ const id = this._loadId;
1508
+ await loading;
1393
1509
 
1394
1510
  // Auto-play the new track unless the caller opted out — lets a
1395
- // controller load/restore/enqueue without forcing playback.
1396
- if (options.autoplay !== false) {
1511
+ // controller load/restore/enqueue without forcing playback. A track
1512
+ // that was superseded while loading must not start (or, in external
1513
+ // mode, request) playback over the one that replaced it.
1514
+ if (options.autoplay !== false && id === this._loadId) {
1397
1515
  this.play()?.catch(() => {});
1398
1516
  }
1399
1517
  }
@@ -1406,31 +1524,58 @@ export class WaveformPlayer {
1406
1524
  * Normalise externally-supplied waveform data into `this.waveformData` and
1407
1525
  * redraw.
1408
1526
  *
1409
- * Accepts several shapes: a `.json` URL (fetched async; peaks and any
1410
- * embedded `markers` are applied on resolve), a JSON-encoded array string,
1411
- * a comma-separated number string, or a plain number array. Malformed
1412
- * input degrades to an empty array rather than throwing.
1527
+ * Accepts several shapes: a `.json` URL (fetched async — a query string
1528
+ * or fragment is fine, which is what {@link WaveformPlayer.getPeaksUrl}
1529
+ * produces for a versioned audio URL), a JSON-encoded array string, a
1530
+ * comma-separated number string, or a plain number array. Malformed input
1531
+ * degrades to an empty array rather than throwing.
1532
+ *
1533
+ * A sidecar may be a bare peaks array or a `{peaks, markers, bpm}` object
1534
+ * (the shape `@arraypress/waveform-gen` writes): its markers apply when the
1535
+ * track has none of its own, and its `bpm` feeds the badge when no `bpm`
1536
+ * option is set. A sidecar that fails to fetch (network error, non-2xx) or
1537
+ * carries no peaks resolves `false` and leaves the canvas as it was —
1538
+ * {@link WaveformPlayer#load} then decodes the audio instead. One that
1539
+ * resolves after a newer load has started is discarded.
1413
1540
  * @param {string|number[]} data - Peaks as an array, a JSON/CSV string, or
1414
1541
  * a URL to a `.json` peaks file.
1415
- * @private
1542
+ * @returns {Promise<boolean>|undefined} For a `.json` URL, a promise of
1543
+ * whether the sidecar was applied; otherwise `undefined` (applied
1544
+ * synchronously).
1416
1545
  */
1417
1546
  setWaveformData(data) {
1418
- // URL to JSON file — fetch peaks and maybe markers
1419
- if (typeof data === 'string' && data.trim().endsWith('.json')) {
1420
- fetch(data.trim())
1421
- .then(r => r.json())
1547
+ // URL to JSON file — fetch peaks and maybe markers / bpm
1548
+ if (typeof data === 'string' && /\.json(?:[?#]|$)/i.test(data.trim())) {
1549
+ const id = this._loadId;
1550
+ return fetch(data.trim())
1551
+ .then(r => {
1552
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
1553
+ return r.json();
1554
+ })
1422
1555
  .then(json => {
1423
- this.waveformData = Array.isArray(json) ? json : (json.peaks || []);
1556
+ if (id !== this._loadId) return false;
1557
+ const peaks = toNumberArray(Array.isArray(json) ? json : json?.peaks, {fallback: []});
1558
+ if (!peaks.length) throw new Error('no peaks');
1559
+ this.waveformData = peaks;
1424
1560
  // A peaks sidecar is a third source of markers, and a remote
1425
1561
  // one — normalize it on the same terms as the option paths.
1426
1562
  if (json.markers && !this.options.markers?.length) {
1427
1563
  this.options.markers = normalizeMarkers(json.markers);
1428
1564
  this.renderMarkers();
1429
1565
  }
1566
+ // A `bpm` option still wins — updateBPMDisplay() prefers it.
1567
+ const bpm = toFiniteNumber(json.bpm, null, {min: 1});
1568
+ if (bpm) {
1569
+ this.detectedBPM = bpm;
1570
+ this.updateBPMDisplay();
1571
+ }
1430
1572
  this.drawWaveform();
1573
+ return true;
1431
1574
  })
1432
- .catch(() => {});
1433
- return;
1575
+ .catch(error => {
1576
+ console.warn('[WaveformPlayer] Could not use peaks file:', data, error);
1577
+ return false;
1578
+ });
1434
1579
  }
1435
1580
 
1436
1581
  // Peaks may arrive as an array, a JSON array string, or a bare
@@ -1462,8 +1607,9 @@ export class WaveformPlayer {
1462
1607
  /**
1463
1608
  * Re-fit the canvas backing store to its parent's width and the configured
1464
1609
  * height, scaled by the device pixel ratio for crisp rendering, then
1465
- * redraw. Guards against running after destruction.
1466
- * @private
1610
+ * redraw. Guards against running after destruction. Public: the resize
1611
+ * observer doesn't reliably fire on a DOM move, so call this after
1612
+ * relocating the player.
1467
1613
  */
1468
1614
  resizeCanvas() {
1469
1615
  // Guard against calls after destruction
@@ -1882,8 +2028,8 @@ export class WaveformPlayer {
1882
2028
  /**
1883
2029
  * `ended` handler (self mode): reset progress and `currentTime` to the
1884
2030
  * start, redraw, reset the time display, dispatch `waveformplayer:ended`
1885
- * (carrying the final time), run {@link WaveformPlayer#onPause}, and fire
1886
- * the `onEnd` callback. No-op during destruction.
2031
+ * (carrying the final time), run {@link WaveformPlayer#onPause} if the
2032
+ * preceding `pause` event hasn't already, and fire the `onEnd` callback. No-op during destruction.
1887
2033
  * @private
1888
2034
  * @fires WaveformPlayer#waveformplayer:ended
1889
2035
  */
@@ -1906,7 +2052,10 @@ export class WaveformPlayer {
1906
2052
  // analytics) don't have to reach into player.audio.
1907
2053
  this._emit('waveformplayer:ended', {player: this, url: this.options.url, currentTime: duration, duration});
1908
2054
 
1909
- this.onPause();
2055
+ // Browsers fire `pause` before `ended` at the end of a track, and
2056
+ // onPause() has usually run already — only settle into paused here
2057
+ // if it hasn't, or listeners see two pause events for one stop.
2058
+ if (this.isPlaying) this.onPause();
1910
2059
 
1911
2060
  if (this.options.onEnd) {
1912
2061
  this.options.onEnd(this);
@@ -1926,21 +2075,9 @@ export class WaveformPlayer {
1926
2075
  if (this.isDestroying) return;
1927
2076
 
1928
2077
  console.error('[WaveformPlayer] Audio error:', error);
1929
- this.hasError = true;
2078
+ this._setError(true);
1930
2079
  this.setLoading(false);
1931
2080
 
1932
- if (this.errorEl) {
1933
- this.errorEl.style.display = 'flex';
1934
- }
1935
-
1936
- if (this.canvas) {
1937
- this.canvas.style.opacity = '0.2';
1938
- }
1939
-
1940
- if (this.playBtn) {
1941
- this.playBtn.disabled = true;
1942
- }
1943
-
1944
2081
  if (this.options.onError) {
1945
2082
  this.options.onError(error, this);
1946
2083
  }
@@ -1965,11 +2102,15 @@ export class WaveformPlayer {
1965
2102
  // setProgress() pushes from the controller — no internal
1966
2103
  // RAF needed. Self-mode keeps the smooth-update loop.
1967
2104
  if (this.isPlaying && this.audio && this.audio.duration) {
2105
+ this._frameAt = Date.now();
1968
2106
  this.updateProgress();
1969
2107
  this.updateTimer = requestAnimationFrame(update);
1970
2108
  }
1971
2109
  };
1972
2110
 
2111
+ // Arm the stall clock too: the native `timeupdate` fallback (see
2112
+ // bindEvents) must not fire before the first frame has had a chance.
2113
+ this._frameAt = Date.now();
1973
2114
  this.updateTimer = requestAnimationFrame(update);
1974
2115
  }
1975
2116
 
@@ -2037,7 +2178,9 @@ export class WaveformPlayer {
2037
2178
  // ============================================
2038
2179
 
2039
2180
  /**
2040
- * Show the detected BPM in the badge, once a value has been detected.
2181
+ * Show the track's BPM in the badge, or hide the badge when the current
2182
+ * track has none — a load resets the detected value, so the previous
2183
+ * track's tempo can't linger on the next one.
2041
2184
  * @private
2042
2185
  */
2043
2186
  updateBPMDisplay() {
@@ -2045,9 +2188,9 @@ export class WaveformPlayer {
2045
2188
  // are pre-generated (so the audio is never decoded) but the BPM is known
2046
2189
  // anyway, e.g. sample-pack previews where the tempo is in the metadata.
2047
2190
  const bpm = this.options.bpm || this.detectedBPM;
2048
- if (this.bpmEl && this.bpmValueEl && bpm) {
2049
- this.bpmValueEl.textContent = Math.round(bpm);
2050
- this.bpmEl.style.display = 'inline-flex';
2191
+ if (this.bpmEl && this.bpmValueEl) {
2192
+ if (bpm) this.bpmValueEl.textContent = Math.round(bpm);
2193
+ this.bpmEl.style.display = bpm ? 'inline-flex' : 'none';
2051
2194
  }
2052
2195
  }
2053
2196
 
@@ -2179,20 +2322,22 @@ export class WaveformPlayer {
2179
2322
  /**
2180
2323
  * Pause audio.
2181
2324
  *
2182
- * In `audioMode: 'external'`, dispatches `waveformplayer:request-pause`
2183
- * (cancelable) and does NOT touch any audio element. See play().
2325
+ * In `audioMode: 'external'`, dispatches a cancelable
2326
+ * `waveformplayer:request-pause` and does NOT touch any audio element.
2327
+ * Mirrors play(): calling preventDefault() on the event vetoes the pause
2328
+ * as far as the player is concerned — it stays `currentlyPlaying` (the
2329
+ * `singlePlay` bookkeeping). Neither event flips the play/pause visual;
2330
+ * that only changes when the controller calls setPlayingState().
2184
2331
  *
2185
2332
  * @fires WaveformPlayer#waveformplayer:request-pause
2186
2333
  */
2187
2334
  pause() {
2188
- if (WaveformPlayer.currentlyPlaying === this) {
2335
+ const accepted = this.options.audioMode !== 'external' ||
2336
+ !this._emit('waveformplayer:request-pause', this._buildTrackDetail(), true).defaultPrevented;
2337
+ if (accepted && WaveformPlayer.currentlyPlaying === this) {
2189
2338
  WaveformPlayer.currentlyPlaying = null;
2190
2339
  }
2191
- if (this.options.audioMode === 'external') {
2192
- this._emit('waveformplayer:request-pause', this._buildTrackDetail(), true);
2193
- return;
2194
- }
2195
- this.audio.pause();
2340
+ this.audio?.pause();
2196
2341
  }
2197
2342
 
2198
2343
  /**
@@ -2255,7 +2400,8 @@ export class WaveformPlayer {
2255
2400
  * external duration for the accessible slider, dispatches
2256
2401
  * `waveformplayer:timeupdate`, runs `onTimeUpdate`, and synthesizes a
2257
2402
  * one-shot `waveformplayer:ended` (with `onEnd`) when progress reaches the
2258
- * end. No-op for a non-positive duration.
2403
+ * end. No-op for a non-positive duration, and while the user is dragging
2404
+ * the playhead (as in self mode).
2259
2405
  *
2260
2406
  * @param {number} currentTime - Current playback position in seconds.
2261
2407
  * @param {number} duration - Total track duration in seconds.
@@ -2264,18 +2410,24 @@ export class WaveformPlayer {
2264
2410
  */
2265
2411
  setProgress(currentTime, duration) {
2266
2412
  if (!duration || duration <= 0) return;
2413
+ // While the user drags, the playhead previews the cursor and the seek
2414
+ // commits on release — the controller's clock mustn't drag it back
2415
+ // (self mode's updateProgress() bails the same way).
2416
+ if (this._dragging) return;
2267
2417
  this.progress = clamp(currentTime / duration);
2268
2418
  // Mirror the existing display update code so callers don't have
2269
2419
  // to know which DOM elements live where.
2270
2420
  if (this.currentTimeEl) this.currentTimeEl.textContent = formatTime(currentTime);
2271
2421
  // Publish the duration unconditionally — the accessible seek slider
2272
2422
  // and keyboard seeking read getSeekDuration()/_extDuration even when
2273
- // there's no time display to update.
2274
- this._extDuration = duration;
2275
- if (this.totalTimeEl && (!this.totalTimeEl.dataset._extSet || this.totalTimeEl.dataset._extDur !== String(duration))) {
2276
- this.totalTimeEl.textContent = formatTime(duration);
2277
- this.totalTimeEl.dataset._extSet = '1';
2278
- this.totalTimeEl.dataset._extDur = String(duration);
2423
+ // there's no time display to update. A new duration (first push, or
2424
+ // a new track — loadTrack() zeroes it) is also what markers were
2425
+ // waiting for: load() ran before any duration existed, so this is
2426
+ // the first point they can be placed.
2427
+ if (duration !== this._extDuration) {
2428
+ this._extDuration = duration;
2429
+ if (this.totalTimeEl) this.totalTimeEl.textContent = formatTime(duration);
2430
+ this.renderMarkers();
2279
2431
  }
2280
2432
  this.drawWaveform?.();
2281
2433
  this.updateActiveMarker();
@@ -2316,13 +2468,16 @@ export class WaveformPlayer {
2316
2468
  /**
2317
2469
  * Seek the owned `<audio>` element to an absolute time, clamped to
2318
2470
  * `[0, duration]`, and refresh progress. Self mode only — a no-op when
2319
- * there is no audio element or duration. External-mode keyboard/click
2320
- * seeks go through {@link WaveformPlayer#seekToSeconds} instead.
2471
+ * there is no audio element or duration, or when `seconds` isn't a finite
2472
+ * number. External-mode keyboard/click seeks go through
2473
+ * {@link WaveformPlayer#seekToSeconds} instead.
2321
2474
  * @param {number} seconds - Target time in seconds.
2322
2475
  */
2323
2476
  seekTo(seconds) {
2324
- if (this.audio && this.audio.duration) {
2325
- this.audio.currentTime = clamp(seconds, 0, this.audio.duration);
2477
+ // Coerce + guard like setVolume(): `audio.currentTime = NaN` throws.
2478
+ const s = Number(seconds);
2479
+ if (this.audio && this.audio.duration && Number.isFinite(s)) {
2480
+ this.audio.currentTime = clamp(s, 0, this.audio.duration);
2326
2481
  this.updateProgress();
2327
2482
  }
2328
2483
  }
@@ -2330,12 +2485,13 @@ export class WaveformPlayer {
2330
2485
  /**
2331
2486
  * Seek the owned `<audio>` element to a fraction of the track, clamped to
2332
2487
  * `[0, 1]`, and refresh progress. Self mode only — a no-op without an audio
2333
- * element or duration.
2488
+ * element or duration, or when `percent` isn't a finite number.
2334
2489
  * @param {number} percent - Position as a fraction from 0 to 1.
2335
2490
  */
2336
2491
  seekToPercent(percent) {
2337
- if (this.audio && this.audio.duration) {
2338
- this.audio.currentTime = this.audio.duration * clamp(percent);
2492
+ const p = Number(percent);
2493
+ if (this.audio && this.audio.duration && Number.isFinite(p)) {
2494
+ this.audio.currentTime = this.audio.duration * clamp(p);
2339
2495
  this.updateProgress();
2340
2496
  }
2341
2497
  }
@@ -2362,7 +2518,8 @@ export class WaveformPlayer {
2362
2518
  * The clamp bounds the range browsers keep audible; the default speed menu
2363
2519
  * offers a narrower 0.5–2, which `playbackRates` can widen up to these
2364
2520
  * bounds. A non-numeric rate is ignored rather than assigned, since
2365
- * `audio.playbackRate = NaN` throws.
2521
+ * `audio.playbackRate = NaN` throws. The rate is also written to
2522
+ * `defaultPlaybackRate`, so it survives the next track load.
2366
2523
  * @param {number} rate - Desired playback rate; clamped to the 0.25–4 range.
2367
2524
  */
2368
2525
  setPlaybackRate(rate) {
@@ -2370,7 +2527,9 @@ export class WaveformPlayer {
2370
2527
 
2371
2528
  const clampedRate = toFiniteNumber(rate, null, {min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX});
2372
2529
  if (clampedRate === null) return;
2373
- this.audio.playbackRate = clampedRate;
2530
+ // The default as well, or the next src change (loadTrack) quietly
2531
+ // drops the listener back to 1x — see initPlaybackSpeed().
2532
+ this.audio.playbackRate = this.audio.defaultPlaybackRate = clampedRate;
2374
2533
  this.options.playbackRate = clampedRate;
2375
2534
 
2376
2535
  this.updateSpeedUI();
@@ -2395,10 +2554,16 @@ export class WaveformPlayer {
2395
2554
  // before teardown — the symmetric counterpart to waveformplayer:ready.
2396
2555
  this._emit('waveformplayer:destroy', {player: this, url: this.options.url});
2397
2556
 
2398
- // Stop playback and animations
2399
- this.pause();
2557
+ // Stop playback and animations. The <audio> itself is paused and
2558
+ // released below; this.pause() isn't called because in external
2559
+ // mode it emits request-pause, and a wrapper remounting an inline
2560
+ // player would pause the controller's (e.g. the bar's) playback.
2400
2561
  this.stopSmoothUpdate();
2401
2562
  clearTimeout(this._markerLabelTimer);
2563
+ clearTimeout(this._readyTimer);
2564
+ // Supersede any in-flight load() so it stops at its next await
2565
+ // instead of decoding, drawing and firing onLoad for a dead player.
2566
+ this._loadId++;
2402
2567
 
2403
2568
  // Tear down every document/container/seek listener in one shot.
2404
2569
  this._ac?.abort();
@@ -2418,10 +2583,13 @@ export class WaveformPlayer {
2418
2583
  // Remove from instances map
2419
2584
  WaveformPlayer.instances.delete(this.id);
2420
2585
 
2421
- // Clear current playing reference if it's this instance
2586
+ // Clear current playing / Media Session references to this instance
2422
2587
  if (WaveformPlayer.currentlyPlaying === this) {
2423
2588
  WaveformPlayer.currentlyPlaying = null;
2424
2589
  }
2590
+ if (WaveformPlayer._sessionOwner === this) {
2591
+ WaveformPlayer._sessionOwner = null;
2592
+ }
2425
2593
 
2426
2594
  // Properly clean up audio element
2427
2595
  if (this.audio) {