@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.
@@ -123,11 +123,11 @@
123
123
  if (element.dataset.buttonStyle) options.buttonStyle = element.dataset.buttonStyle;
124
124
  setLength("buttonSize");
125
125
  setLength("buttonRadius");
126
+ if (element.dataset.color) options.waveformColor = parseColorValue(element.dataset.color);
127
+ if (element.dataset.theme) options.colorPreset = element.dataset.theme;
126
128
  if (element.dataset.colorPreset) options.colorPreset = element.dataset.colorPreset;
127
129
  if (element.dataset.waveformColor) options.waveformColor = parseColorValue(element.dataset.waveformColor);
128
130
  if (element.dataset.progressColor) options.progressColor = parseColorValue(element.dataset.progressColor);
129
- if (element.dataset.color) options.waveformColor = element.dataset.color;
130
- if (element.dataset.theme) options.colorPreset = element.dataset.theme;
131
131
  setBool("autoplay");
132
132
  setBool("showControls");
133
133
  setBool("showInfo");
@@ -282,6 +282,9 @@
282
282
  }
283
283
 
284
284
  // src/js/drawing.js
285
+ function fitBars(canvas, pitch) {
286
+ return pitch > 0 ? Math.floor(canvas.width / pitch) : 0;
287
+ }
285
288
  function makeFill(ctx, value, canvas, options) {
286
289
  if (!Array.isArray(value)) return value;
287
290
  if (value.length < 2) return value[0];
@@ -330,7 +333,7 @@
330
333
  const dpr = window.devicePixelRatio || 1;
331
334
  const barWidth = options.barWidth * dpr;
332
335
  const barSpacing = options.barSpacing * dpr;
333
- const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
336
+ const barCount = fitBars(canvas, barWidth + barSpacing);
334
337
  const resampledPeaks = resampleData(peaks, barCount);
335
338
  const height = canvas.height;
336
339
  const progressWidth = progress * canvas.width;
@@ -364,7 +367,7 @@
364
367
  const dpr = window.devicePixelRatio || 1;
365
368
  const barWidth = options.barWidth * dpr;
366
369
  const barSpacing = options.barSpacing * dpr;
367
- const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
370
+ const barCount = fitBars(canvas, barWidth + barSpacing);
368
371
  const resampledPeaks = resampleData(peaks, barCount);
369
372
  const height = canvas.height;
370
373
  const centerY = height / 2;
@@ -459,7 +462,7 @@
459
462
  const dpr = window.devicePixelRatio || 1;
460
463
  const barWidth = (options.barWidth || 3) * dpr;
461
464
  const barSpacing = (options.barSpacing || 1) * dpr;
462
- const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
465
+ const barCount = fitBars(canvas, barWidth + barSpacing);
463
466
  const resampledPeaks = resampleData(peaks, barCount);
464
467
  const height = canvas.height;
465
468
  const blockSize = 4 * dpr;
@@ -488,7 +491,7 @@
488
491
  const dpr = window.devicePixelRatio || 1;
489
492
  const barWidth = (options.barWidth || 2) * dpr;
490
493
  const barSpacing = (options.barSpacing || 3) * dpr;
491
- const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
494
+ const barCount = fitBars(canvas, barWidth + barSpacing);
492
495
  const resampledPeaks = resampleData(peaks, barCount);
493
496
  const height = canvas.height;
494
497
  const dotRadius = Math.max(1.5 * dpr, barWidth / 2);
@@ -559,7 +562,7 @@
559
562
  const channelData = buffer.getChannelData(0);
560
563
  const sampleRate = buffer.sampleRate;
561
564
  const onsets = detectOnsets(channelData, sampleRate);
562
- if (onsets.length < 2) return 120;
565
+ if (onsets.length < 2) return null;
563
566
  const intervals = [];
564
567
  for (let i = 1; i < onsets.length; i++) {
565
568
  intervals.push((onsets[i] - onsets[i - 1]) / sampleRate);
@@ -573,13 +576,14 @@
573
576
  }
574
577
  });
575
578
  let maxCount = 0;
576
- let detectedBPM = 120;
579
+ let detectedBPM = null;
577
580
  for (const [tempo, count] of Object.entries(tempoGroups)) {
578
581
  if (count > maxCount) {
579
582
  maxCount = count;
580
583
  detectedBPM = parseInt(tempo);
581
584
  }
582
585
  }
586
+ if (detectedBPM === null) return null;
583
587
  if (detectedBPM < 70 && tempoGroups[detectedBPM * 2]) {
584
588
  detectedBPM *= 2;
585
589
  } else if (detectedBPM > 160 && tempoGroups[Math.round(detectedBPM / 2)]) {
@@ -912,7 +916,9 @@
912
916
  var NUMBERS = {
913
917
  height: { min: 1, integer: true },
914
918
  samples: { min: 1, integer: true },
915
- barWidth: { min: 0 },
919
+ // A zero-width bar is invisible anyway, and zero width + zero spacing
920
+ // made the drawers' bar count Infinity (see fitBars in drawing.js).
921
+ barWidth: { min: 0.1 },
916
922
  barSpacing: { min: 0 },
917
923
  barRadius: { min: 0 },
918
924
  bpm: { min: 1 },
@@ -1079,6 +1085,7 @@
1079
1085
  this.hasError = false;
1080
1086
  this.updateTimer = null;
1081
1087
  this.resizeObserver = null;
1088
+ this._loadId = 0;
1082
1089
  this._ac = new AbortController();
1083
1090
  this.id = this.container.id || generateId(this.options.url);
1084
1091
  _WaveformPlayer.instances.set(this.id, this);
@@ -1090,7 +1097,7 @@
1090
1097
  this._ac.abort();
1091
1098
  throw error;
1092
1099
  }
1093
- setTimeout(() => {
1100
+ this._readyTimer = setTimeout(() => {
1094
1101
  this._emit("waveformplayer:ready", { player: this, url: this.options.url });
1095
1102
  }, 100);
1096
1103
  }
@@ -1145,8 +1152,9 @@
1145
1152
  this.bindEvents();
1146
1153
  this.setupResizeObserver();
1147
1154
  requestAnimationFrame(() => {
1155
+ if (this.isDestroying) return;
1148
1156
  this.resizeCanvas();
1149
- if (this.options.url) {
1157
+ if (this.options.url && !this._loadId) {
1150
1158
  this.load(this.options.url).then(() => {
1151
1159
  if (this.options.autoplay) {
1152
1160
  this.play()?.catch(() => {
@@ -1456,7 +1464,7 @@
1456
1464
  */
1457
1465
  initPlaybackSpeed() {
1458
1466
  if (this.audio && this.options.playbackRate && this.options.playbackRate !== 1) {
1459
- this.audio.playbackRate = this.options.playbackRate;
1467
+ this.audio.playbackRate = this.audio.defaultPlaybackRate = this.options.playbackRate;
1460
1468
  }
1461
1469
  if (this.options.showPlaybackSpeed) {
1462
1470
  this.initSpeedControls();
@@ -1733,6 +1741,7 @@
1733
1741
  initMediaSession() {
1734
1742
  if (!("mediaSession" in navigator) || !this.options.enableMediaSession) return;
1735
1743
  if (!this.audio) return;
1744
+ _WaveformPlayer._sessionOwner = this;
1736
1745
  this._applyMediaMetadata();
1737
1746
  navigator.mediaSession.setActionHandler("play", () => this.play());
1738
1747
  navigator.mediaSession.setActionHandler("pause", () => this.pause());
@@ -1785,14 +1794,26 @@
1785
1794
  try {
1786
1795
  if (state === "playing") this.initMediaSession();
1787
1796
  navigator.mediaSession.playbackState = state;
1788
- const d = this.audio.duration;
1789
- if (navigator.mediaSession.setPositionState && d && isFinite(d)) {
1790
- navigator.mediaSession.setPositionState({
1791
- duration: d,
1792
- playbackRate: this.audio.playbackRate || 1,
1793
- position: clamp(this.audio.currentTime, 0, d)
1794
- });
1795
- }
1797
+ this._updatePositionState();
1798
+ } catch (e) {
1799
+ }
1800
+ }
1801
+ /**
1802
+ * Publish duration, rate and position to the lock-screen scrubber. Runs
1803
+ * on play/pause and on the element's `seeked` / `ratechange`, so the
1804
+ * scrubber doesn't drift after a seek or a speed change until the next
1805
+ * play/pause. Only the player that owns the (global) session writes it.
1806
+ * @private
1807
+ */
1808
+ _updatePositionState() {
1809
+ const d = this.audio?.duration;
1810
+ if (_WaveformPlayer._sessionOwner !== this || !navigator.mediaSession?.setPositionState || !(d && isFinite(d))) return;
1811
+ try {
1812
+ navigator.mediaSession.setPositionState({
1813
+ duration: d,
1814
+ playbackRate: this.audio.playbackRate || 1,
1815
+ position: clamp(this.audio.currentTime, 0, d)
1816
+ });
1796
1817
  } catch (e) {
1797
1818
  }
1798
1819
  }
@@ -1818,6 +1839,11 @@
1818
1839
  this.audio.addEventListener("pause", () => this.onPause());
1819
1840
  this.audio.addEventListener("ended", () => this.onEnded());
1820
1841
  this.audio.addEventListener("error", (e) => this.onError(e));
1842
+ this.audio.addEventListener("seeked", () => this._updatePositionState());
1843
+ this.audio.addEventListener("ratechange", () => this._updatePositionState());
1844
+ this.audio.addEventListener("timeupdate", () => {
1845
+ if (this.isPlaying && Date.now() - this._frameAt > 500) this.updateProgress();
1846
+ });
1821
1847
  }
1822
1848
  this.canvas.addEventListener("click", (e) => this.handleCanvasClick(e));
1823
1849
  this._dragging = false;
@@ -1904,56 +1930,71 @@
1904
1930
  * accessible name are written *before* the metadata wait, as are peaks
1905
1931
  * supplied via the `waveform` option — none of them need anything from the
1906
1932
  * audio element, and behind the wait they blink in on a slow origin.
1907
- * Without inline peaks the waveform is decoded from the audio instead; a
1908
- * decode failure falls back to a placeholder. The `onLoad` callback fires
1909
- * on success.
1933
+ * Without inline peaks — or when a `.json` peaks sidecar can't be fetched —
1934
+ * the waveform is decoded from the audio instead; a decode failure falls
1935
+ * back to a placeholder. The `onLoad` callback fires on success.
1936
+ *
1937
+ * Every call supersedes the previous one: a load that is overtaken while
1938
+ * it awaits (metadata, a sidecar fetch, the decode) stops there without
1939
+ * touching the player, so a slow first track can't land its peaks, BPM,
1940
+ * error or loading state on the track that replaced it.
1941
+ *
1942
+ * Loading a *different* URL also resets what the previous track left
1943
+ * behind (see {@link WaveformPlayer#_resetTrack}); reloading the same URL
1944
+ * — e.g. a retry after an error — keeps the drawn waveform. Either way the
1945
+ * error state is cleared, so a retry re-enables the player.
1910
1946
  * @param {string} url - Audio URL.
1911
1947
  * @returns {Promise<void>} Resolves once loading settles (errors are caught
1912
1948
  * internally and surfaced through {@link WaveformPlayer#onError}).
1913
1949
  */
1914
1950
  async load(url) {
1951
+ const id = ++this._loadId;
1952
+ const audio = this.audio;
1915
1953
  try {
1954
+ if (url !== this.options.url) this._resetTrack();
1916
1955
  this.setLoading(true);
1917
1956
  this.progress = 0;
1918
- this.hasError = false;
1957
+ this._setError(false);
1919
1958
  this.container.classList.remove("waveform-is-placeholder");
1920
- const hasInlinePeaks = !!this.options.waveform;
1921
- if (hasInlinePeaks) {
1922
- this.setWaveformData(this.options.waveform);
1923
- }
1959
+ this.detectedBPM = null;
1960
+ this.updateBPMDisplay();
1961
+ this.options.url = url;
1962
+ const inlinePeaks = this.options.waveform;
1963
+ const sidecar = inlinePeaks ? this.setWaveformData(inlinePeaks) : null;
1924
1964
  const title = this.options.title || extractTitleFromUrl(url);
1925
1965
  if (this.titleEl) {
1926
1966
  this.titleEl.textContent = title;
1927
1967
  }
1928
1968
  this.applySeekLabel(title);
1929
- if (this.audio) {
1930
- this.audio.src = url;
1931
- if (this.audio.preload !== "none") {
1969
+ if (audio) {
1970
+ audio.src = url;
1971
+ if (audio.preload !== "none") {
1932
1972
  await new Promise((resolve, reject) => {
1933
- const metadataHandler = () => {
1934
- this.audio.removeEventListener("loadedmetadata", metadataHandler);
1935
- this.audio.removeEventListener("error", errorHandler);
1936
- resolve();
1973
+ const settle = (fn) => (e) => {
1974
+ audio.removeEventListener("loadedmetadata", metadataHandler);
1975
+ audio.removeEventListener("error", errorHandler);
1976
+ fn(e);
1937
1977
  };
1938
- const errorHandler = (e) => {
1939
- this.audio.removeEventListener("loadedmetadata", metadataHandler);
1940
- this.audio.removeEventListener("error", errorHandler);
1941
- reject(e);
1942
- };
1943
- this.audio.addEventListener("loadedmetadata", metadataHandler);
1944
- this.audio.addEventListener("error", errorHandler);
1978
+ const metadataHandler = settle(resolve);
1979
+ const errorHandler = settle(reject);
1980
+ audio.addEventListener("loadedmetadata", metadataHandler);
1981
+ audio.addEventListener("error", errorHandler);
1945
1982
  });
1946
1983
  }
1947
1984
  }
1948
- if (!hasInlinePeaks) {
1985
+ const sidecarOk = await sidecar;
1986
+ if (id !== this._loadId) return;
1987
+ if (!inlinePeaks || sidecarOk === false) {
1949
1988
  try {
1950
1989
  const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
1990
+ if (id !== this._loadId) return;
1951
1991
  this.waveformData = result.peaks;
1952
1992
  if (result.bpm) {
1953
1993
  this.detectedBPM = result.bpm;
1954
1994
  this.updateBPMDisplay();
1955
1995
  }
1956
1996
  } catch (error) {
1997
+ if (id !== this._loadId) return;
1957
1998
  console.warn("[WaveformPlayer] Using placeholder waveform:", error);
1958
1999
  this.waveformData = generatePlaceholderWaveform(this.options.samples);
1959
2000
  this.container.classList.add("waveform-is-placeholder");
@@ -1965,11 +2006,43 @@
1965
2006
  this.options.onLoad(this);
1966
2007
  }
1967
2008
  } catch (error) {
1968
- this.onError(error);
2009
+ if (id === this._loadId && !this.hasError) this.onError(error);
1969
2010
  } finally {
1970
- this.setLoading(false);
2011
+ if (id === this._loadId) this.setLoading(false);
1971
2012
  }
1972
2013
  }
2014
+ /**
2015
+ * Forget everything the previous track left on the player: its peaks,
2016
+ * progress, duration (external mode), time readout and marker buttons.
2017
+ * Shared by {@link WaveformPlayer#loadTrack} and a {@link WaveformPlayer#load}
2018
+ * of a different URL, so neither path can show the old track's `1:30` or
2019
+ * place the new track's markers against the old duration. Per-track
2020
+ * *options* are reset by `loadTrack()`, which is the path that receives them.
2021
+ * @private
2022
+ */
2023
+ _resetTrack() {
2024
+ this.progress = 0;
2025
+ this.waveformData = [];
2026
+ this._extDuration = 0;
2027
+ this._extEnded = false;
2028
+ if (this.currentTimeEl) this.currentTimeEl.textContent = "0:00";
2029
+ if (this.totalTimeEl) this.totalTimeEl.textContent = "0:00";
2030
+ if (this.markersContainer) this.markersContainer.innerHTML = "";
2031
+ }
2032
+ /**
2033
+ * Show or clear the error state: the overlay, the dimmed canvas and the
2034
+ * disabled play button. The one place both {@link WaveformPlayer#onError}
2035
+ * and a fresh {@link WaveformPlayer#load} flip it, so a retry can't leave
2036
+ * half of it behind.
2037
+ * @param {boolean} on - True to enter the error state, false to clear it.
2038
+ * @private
2039
+ */
2040
+ _setError(on) {
2041
+ this.hasError = on;
2042
+ if (this.errorEl) this.errorEl.style.display = on ? "flex" : "none";
2043
+ if (this.canvas) this.canvas.style.opacity = on ? "0.2" : "1";
2044
+ if (this.playBtn) this.playBtn.disabled = on;
2045
+ }
1973
2046
  /**
1974
2047
  * Swap the player to a new track at runtime.
1975
2048
  *
@@ -1977,14 +2050,22 @@
1977
2050
  * clears error/marker/progress state, merges the new metadata into
1978
2051
  * `this.options`, updates the artist/artwork DOM, then calls
1979
2052
  * {@link WaveformPlayer#load}. Auto-plays the new track unless
1980
- * `options.autoplay === false`.
2053
+ * `options.autoplay === false` — and only if no later `loadTrack()` /
2054
+ * `load()` has superseded this one by the time it finishes loading.
2055
+ *
2056
+ * Per-track options the caller doesn't repeat are reset rather than
2057
+ * inherited from the previous track: `markers`, `waveform`, `bpm` and
2058
+ * `album`.
1981
2059
  * @param {string} url - Audio URL.
1982
2060
  * @param {string|null} [title=null] - Track title; keeps the existing
1983
- * title when null.
2061
+ * title when null. (Deliberate: a controller that only swaps the
2062
+ * audio keeps the label it set. Pass `''` to derive the title from the
2063
+ * URL instead.)
1984
2064
  * @param {string|null} [artist=null] - Track artist; pass `''` to hide
1985
2065
  * the artist row, or null to keep the existing one.
1986
2066
  * @param {Object} [options={}] - Additional options to merge (e.g.
1987
- * `preload`, `artwork`, `artworkAlt`, `markers`, `autoplay`).
2067
+ * `preload`, `artwork`, `artworkAlt`, `markers`, `bpm`, `album`,
2068
+ * `autoplay`).
1988
2069
  * @returns {Promise<void>}
1989
2070
  */
1990
2071
  async loadTrack(url, title = null, artist = null, options = {}) {
@@ -1997,18 +2078,7 @@
1997
2078
  this.audio.src = "";
1998
2079
  this.audio.load();
1999
2080
  }
2000
- this.hasError = false;
2001
- if (this.errorEl) {
2002
- this.errorEl.style.display = "none";
2003
- }
2004
- if (this.canvas) {
2005
- this.canvas.style.opacity = "1";
2006
- }
2007
- if (this.playBtn) {
2008
- this.playBtn.disabled = false;
2009
- }
2010
- this.progress = 0;
2011
- this.waveformData = [];
2081
+ this._resetTrack();
2012
2082
  this.options = normalizeOptions(mergeOptions(this.options, {
2013
2083
  url,
2014
2084
  title: title === null ? this.options.title : title,
@@ -2023,6 +2093,9 @@
2023
2093
  } else if (hasArtworkOption) {
2024
2094
  this.options.artworkAlt = this.options.artwork ? DEFAULT_OPTIONS.artworkAlt : "";
2025
2095
  }
2096
+ for (const key of ["bpm", "album"]) {
2097
+ if (options[key] == null) this.options[key] = DEFAULT_OPTIONS[key];
2098
+ }
2026
2099
  if (options.preload && this.audio) {
2027
2100
  this.audio.preload = this.options.preload;
2028
2101
  }
@@ -2040,8 +2113,10 @@
2040
2113
  }
2041
2114
  this.options.markers = options.markers ? normalizeMarkers(options.markers) : [];
2042
2115
  this.options.waveform = options.waveform || null;
2043
- await this.load(url);
2044
- if (options.autoplay !== false) {
2116
+ const loading = this.load(url);
2117
+ const id = this._loadId;
2118
+ await loading;
2119
+ if (options.autoplay !== false && id === this._loadId) {
2045
2120
  this.play()?.catch(() => {
2046
2121
  });
2047
2122
  }
@@ -2053,26 +2128,51 @@
2053
2128
  * Normalise externally-supplied waveform data into `this.waveformData` and
2054
2129
  * redraw.
2055
2130
  *
2056
- * Accepts several shapes: a `.json` URL (fetched async; peaks and any
2057
- * embedded `markers` are applied on resolve), a JSON-encoded array string,
2058
- * a comma-separated number string, or a plain number array. Malformed
2059
- * input degrades to an empty array rather than throwing.
2131
+ * Accepts several shapes: a `.json` URL (fetched async — a query string
2132
+ * or fragment is fine, which is what {@link WaveformPlayer.getPeaksUrl}
2133
+ * produces for a versioned audio URL), a JSON-encoded array string, a
2134
+ * comma-separated number string, or a plain number array. Malformed input
2135
+ * degrades to an empty array rather than throwing.
2136
+ *
2137
+ * A sidecar may be a bare peaks array or a `{peaks, markers, bpm}` object
2138
+ * (the shape `@arraypress/waveform-gen` writes): its markers apply when the
2139
+ * track has none of its own, and its `bpm` feeds the badge when no `bpm`
2140
+ * option is set. A sidecar that fails to fetch (network error, non-2xx) or
2141
+ * carries no peaks resolves `false` and leaves the canvas as it was —
2142
+ * {@link WaveformPlayer#load} then decodes the audio instead. One that
2143
+ * resolves after a newer load has started is discarded.
2060
2144
  * @param {string|number[]} data - Peaks as an array, a JSON/CSV string, or
2061
2145
  * a URL to a `.json` peaks file.
2062
- * @private
2146
+ * @returns {Promise<boolean>|undefined} For a `.json` URL, a promise of
2147
+ * whether the sidecar was applied; otherwise `undefined` (applied
2148
+ * synchronously).
2063
2149
  */
2064
2150
  setWaveformData(data) {
2065
- if (typeof data === "string" && data.trim().endsWith(".json")) {
2066
- fetch(data.trim()).then((r) => r.json()).then((json) => {
2067
- this.waveformData = Array.isArray(json) ? json : json.peaks || [];
2151
+ if (typeof data === "string" && /\.json(?:[?#]|$)/i.test(data.trim())) {
2152
+ const id = this._loadId;
2153
+ return fetch(data.trim()).then((r) => {
2154
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
2155
+ return r.json();
2156
+ }).then((json) => {
2157
+ if (id !== this._loadId) return false;
2158
+ const peaks = toNumberArray(Array.isArray(json) ? json : json?.peaks, { fallback: [] });
2159
+ if (!peaks.length) throw new Error("no peaks");
2160
+ this.waveformData = peaks;
2068
2161
  if (json.markers && !this.options.markers?.length) {
2069
2162
  this.options.markers = normalizeMarkers(json.markers);
2070
2163
  this.renderMarkers();
2071
2164
  }
2165
+ const bpm = toFiniteNumber(json.bpm, null, { min: 1 });
2166
+ if (bpm) {
2167
+ this.detectedBPM = bpm;
2168
+ this.updateBPMDisplay();
2169
+ }
2072
2170
  this.drawWaveform();
2073
- }).catch(() => {
2171
+ return true;
2172
+ }).catch((error) => {
2173
+ console.warn("[WaveformPlayer] Could not use peaks file:", data, error);
2174
+ return false;
2074
2175
  });
2075
- return;
2076
2176
  }
2077
2177
  this.waveformData = toNumberArray(data, { fallback: [] });
2078
2178
  this.drawWaveform();
@@ -2096,8 +2196,9 @@
2096
2196
  /**
2097
2197
  * Re-fit the canvas backing store to its parent's width and the configured
2098
2198
  * height, scaled by the device pixel ratio for crisp rendering, then
2099
- * redraw. Guards against running after destruction.
2100
- * @private
2199
+ * redraw. Guards against running after destruction. Public: the resize
2200
+ * observer doesn't reliably fire on a DOM move, so call this after
2201
+ * relocating the player.
2101
2202
  */
2102
2203
  resizeCanvas() {
2103
2204
  if (!this.canvas || this.isDestroying) {
@@ -2431,8 +2532,8 @@
2431
2532
  /**
2432
2533
  * `ended` handler (self mode): reset progress and `currentTime` to the
2433
2534
  * start, redraw, reset the time display, dispatch `waveformplayer:ended`
2434
- * (carrying the final time), run {@link WaveformPlayer#onPause}, and fire
2435
- * the `onEnd` callback. No-op during destruction.
2535
+ * (carrying the final time), run {@link WaveformPlayer#onPause} if the
2536
+ * preceding `pause` event hasn't already, and fire the `onEnd` callback. No-op during destruction.
2436
2537
  * @private
2437
2538
  * @fires WaveformPlayer#waveformplayer:ended
2438
2539
  */
@@ -2446,7 +2547,7 @@
2446
2547
  this.currentTimeEl.textContent = "0:00";
2447
2548
  }
2448
2549
  this._emit("waveformplayer:ended", { player: this, url: this.options.url, currentTime: duration, duration });
2449
- this.onPause();
2550
+ if (this.isPlaying) this.onPause();
2450
2551
  if (this.options.onEnd) {
2451
2552
  this.options.onEnd(this);
2452
2553
  }
@@ -2462,17 +2563,8 @@
2462
2563
  onError(error) {
2463
2564
  if (this.isDestroying) return;
2464
2565
  console.error("[WaveformPlayer] Audio error:", error);
2465
- this.hasError = true;
2566
+ this._setError(true);
2466
2567
  this.setLoading(false);
2467
- if (this.errorEl) {
2468
- this.errorEl.style.display = "flex";
2469
- }
2470
- if (this.canvas) {
2471
- this.canvas.style.opacity = "0.2";
2472
- }
2473
- if (this.playBtn) {
2474
- this.playBtn.disabled = true;
2475
- }
2476
2568
  if (this.options.onError) {
2477
2569
  this.options.onError(error, this);
2478
2570
  }
@@ -2491,10 +2583,12 @@
2491
2583
  this.stopSmoothUpdate();
2492
2584
  const update = () => {
2493
2585
  if (this.isPlaying && this.audio && this.audio.duration) {
2586
+ this._frameAt = Date.now();
2494
2587
  this.updateProgress();
2495
2588
  this.updateTimer = requestAnimationFrame(update);
2496
2589
  }
2497
2590
  };
2591
+ this._frameAt = Date.now();
2498
2592
  this.updateTimer = requestAnimationFrame(update);
2499
2593
  }
2500
2594
  /**
@@ -2547,14 +2641,16 @@
2547
2641
  // UI Updates
2548
2642
  // ============================================
2549
2643
  /**
2550
- * Show the detected BPM in the badge, once a value has been detected.
2644
+ * Show the track's BPM in the badge, or hide the badge when the current
2645
+ * track has none — a load resets the detected value, so the previous
2646
+ * track's tempo can't linger on the next one.
2551
2647
  * @private
2552
2648
  */
2553
2649
  updateBPMDisplay() {
2554
2650
  const bpm = this.options.bpm || this.detectedBPM;
2555
- if (this.bpmEl && this.bpmValueEl && bpm) {
2556
- this.bpmValueEl.textContent = Math.round(bpm);
2557
- this.bpmEl.style.display = "inline-flex";
2651
+ if (this.bpmEl && this.bpmValueEl) {
2652
+ if (bpm) this.bpmValueEl.textContent = Math.round(bpm);
2653
+ this.bpmEl.style.display = bpm ? "inline-flex" : "none";
2558
2654
  }
2559
2655
  }
2560
2656
  /**
@@ -2673,20 +2769,21 @@
2673
2769
  /**
2674
2770
  * Pause audio.
2675
2771
  *
2676
- * In `audioMode: 'external'`, dispatches `waveformplayer:request-pause`
2677
- * (cancelable) and does NOT touch any audio element. See play().
2772
+ * In `audioMode: 'external'`, dispatches a cancelable
2773
+ * `waveformplayer:request-pause` and does NOT touch any audio element.
2774
+ * Mirrors play(): calling preventDefault() on the event vetoes the pause
2775
+ * as far as the player is concerned — it stays `currentlyPlaying` (the
2776
+ * `singlePlay` bookkeeping). Neither event flips the play/pause visual;
2777
+ * that only changes when the controller calls setPlayingState().
2678
2778
  *
2679
2779
  * @fires WaveformPlayer#waveformplayer:request-pause
2680
2780
  */
2681
2781
  pause() {
2682
- if (_WaveformPlayer.currentlyPlaying === this) {
2782
+ const accepted = this.options.audioMode !== "external" || !this._emit("waveformplayer:request-pause", this._buildTrackDetail(), true).defaultPrevented;
2783
+ if (accepted && _WaveformPlayer.currentlyPlaying === this) {
2683
2784
  _WaveformPlayer.currentlyPlaying = null;
2684
2785
  }
2685
- if (this.options.audioMode === "external") {
2686
- this._emit("waveformplayer:request-pause", this._buildTrackDetail(), true);
2687
- return;
2688
- }
2689
- this.audio.pause();
2786
+ this.audio?.pause();
2690
2787
  }
2691
2788
  /**
2692
2789
  * Build the track detail object dispatched by request-play /
@@ -2746,7 +2843,8 @@
2746
2843
  * external duration for the accessible slider, dispatches
2747
2844
  * `waveformplayer:timeupdate`, runs `onTimeUpdate`, and synthesizes a
2748
2845
  * one-shot `waveformplayer:ended` (with `onEnd`) when progress reaches the
2749
- * end. No-op for a non-positive duration.
2846
+ * end. No-op for a non-positive duration, and while the user is dragging
2847
+ * the playhead (as in self mode).
2750
2848
  *
2751
2849
  * @param {number} currentTime - Current playback position in seconds.
2752
2850
  * @param {number} duration - Total track duration in seconds.
@@ -2755,13 +2853,13 @@
2755
2853
  */
2756
2854
  setProgress(currentTime, duration) {
2757
2855
  if (!duration || duration <= 0) return;
2856
+ if (this._dragging) return;
2758
2857
  this.progress = clamp(currentTime / duration);
2759
2858
  if (this.currentTimeEl) this.currentTimeEl.textContent = formatTime(currentTime);
2760
- this._extDuration = duration;
2761
- if (this.totalTimeEl && (!this.totalTimeEl.dataset._extSet || this.totalTimeEl.dataset._extDur !== String(duration))) {
2762
- this.totalTimeEl.textContent = formatTime(duration);
2763
- this.totalTimeEl.dataset._extSet = "1";
2764
- this.totalTimeEl.dataset._extDur = String(duration);
2859
+ if (duration !== this._extDuration) {
2860
+ this._extDuration = duration;
2861
+ if (this.totalTimeEl) this.totalTimeEl.textContent = formatTime(duration);
2862
+ this.renderMarkers();
2765
2863
  }
2766
2864
  this.drawWaveform?.();
2767
2865
  this.updateActiveMarker();
@@ -2793,25 +2891,28 @@
2793
2891
  /**
2794
2892
  * Seek the owned `<audio>` element to an absolute time, clamped to
2795
2893
  * `[0, duration]`, and refresh progress. Self mode only — a no-op when
2796
- * there is no audio element or duration. External-mode keyboard/click
2797
- * seeks go through {@link WaveformPlayer#seekToSeconds} instead.
2894
+ * there is no audio element or duration, or when `seconds` isn't a finite
2895
+ * number. External-mode keyboard/click seeks go through
2896
+ * {@link WaveformPlayer#seekToSeconds} instead.
2798
2897
  * @param {number} seconds - Target time in seconds.
2799
2898
  */
2800
2899
  seekTo(seconds) {
2801
- if (this.audio && this.audio.duration) {
2802
- this.audio.currentTime = clamp(seconds, 0, this.audio.duration);
2900
+ const s = Number(seconds);
2901
+ if (this.audio && this.audio.duration && Number.isFinite(s)) {
2902
+ this.audio.currentTime = clamp(s, 0, this.audio.duration);
2803
2903
  this.updateProgress();
2804
2904
  }
2805
2905
  }
2806
2906
  /**
2807
2907
  * Seek the owned `<audio>` element to a fraction of the track, clamped to
2808
2908
  * `[0, 1]`, and refresh progress. Self mode only — a no-op without an audio
2809
- * element or duration.
2909
+ * element or duration, or when `percent` isn't a finite number.
2810
2910
  * @param {number} percent - Position as a fraction from 0 to 1.
2811
2911
  */
2812
2912
  seekToPercent(percent) {
2813
- if (this.audio && this.audio.duration) {
2814
- this.audio.currentTime = this.audio.duration * clamp(percent);
2913
+ const p = Number(percent);
2914
+ if (this.audio && this.audio.duration && Number.isFinite(p)) {
2915
+ this.audio.currentTime = this.audio.duration * clamp(p);
2815
2916
  this.updateProgress();
2816
2917
  }
2817
2918
  }
@@ -2834,14 +2935,15 @@
2834
2935
  * The clamp bounds the range browsers keep audible; the default speed menu
2835
2936
  * offers a narrower 0.5–2, which `playbackRates` can widen up to these
2836
2937
  * bounds. A non-numeric rate is ignored rather than assigned, since
2837
- * `audio.playbackRate = NaN` throws.
2938
+ * `audio.playbackRate = NaN` throws. The rate is also written to
2939
+ * `defaultPlaybackRate`, so it survives the next track load.
2838
2940
  * @param {number} rate - Desired playback rate; clamped to the 0.25–4 range.
2839
2941
  */
2840
2942
  setPlaybackRate(rate) {
2841
2943
  if (!this.audio) return;
2842
2944
  const clampedRate = toFiniteNumber(rate, null, { min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX });
2843
2945
  if (clampedRate === null) return;
2844
- this.audio.playbackRate = clampedRate;
2946
+ this.audio.playbackRate = this.audio.defaultPlaybackRate = clampedRate;
2845
2947
  this.options.playbackRate = clampedRate;
2846
2948
  this.updateSpeedUI();
2847
2949
  }
@@ -2859,9 +2961,10 @@
2859
2961
  destroy() {
2860
2962
  this.isDestroying = true;
2861
2963
  this._emit("waveformplayer:destroy", { player: this, url: this.options.url });
2862
- this.pause();
2863
2964
  this.stopSmoothUpdate();
2864
2965
  clearTimeout(this._markerLabelTimer);
2966
+ clearTimeout(this._readyTimer);
2967
+ this._loadId++;
2865
2968
  this._ac?.abort();
2866
2969
  if (this.resizeObserver) {
2867
2970
  this.resizeObserver.disconnect();
@@ -2875,6 +2978,9 @@
2875
2978
  if (_WaveformPlayer.currentlyPlaying === this) {
2876
2979
  _WaveformPlayer.currentlyPlaying = null;
2877
2980
  }
2981
+ if (_WaveformPlayer._sessionOwner === this) {
2982
+ _WaveformPlayer._sessionOwner = null;
2983
+ }
2878
2984
  if (this.audio) {
2879
2985
  this.audio.pause();
2880
2986
  this.audio.src = "";