@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.
@@ -148,11 +148,11 @@ function parseDataAttributes(element) {
148
148
  if (element.dataset.buttonStyle) options.buttonStyle = element.dataset.buttonStyle;
149
149
  setLength("buttonSize");
150
150
  setLength("buttonRadius");
151
+ if (element.dataset.color) options.waveformColor = parseColorValue(element.dataset.color);
152
+ if (element.dataset.theme) options.colorPreset = element.dataset.theme;
151
153
  if (element.dataset.colorPreset) options.colorPreset = element.dataset.colorPreset;
152
154
  if (element.dataset.waveformColor) options.waveformColor = parseColorValue(element.dataset.waveformColor);
153
155
  if (element.dataset.progressColor) options.progressColor = parseColorValue(element.dataset.progressColor);
154
- if (element.dataset.color) options.waveformColor = element.dataset.color;
155
- if (element.dataset.theme) options.colorPreset = element.dataset.theme;
156
156
  setBool("autoplay");
157
157
  setBool("showControls");
158
158
  setBool("showInfo");
@@ -307,6 +307,9 @@ function resampleData(data, targetLength) {
307
307
  }
308
308
 
309
309
  // src/js/drawing.js
310
+ function fitBars(canvas, pitch) {
311
+ return pitch > 0 ? Math.floor(canvas.width / pitch) : 0;
312
+ }
310
313
  function makeFill(ctx, value, canvas, options) {
311
314
  if (!Array.isArray(value)) return value;
312
315
  if (value.length < 2) return value[0];
@@ -355,7 +358,7 @@ function drawBars(ctx, canvas, peaks, progress, options) {
355
358
  const dpr = window.devicePixelRatio || 1;
356
359
  const barWidth = options.barWidth * dpr;
357
360
  const barSpacing = options.barSpacing * dpr;
358
- const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
361
+ const barCount = fitBars(canvas, barWidth + barSpacing);
359
362
  const resampledPeaks = resampleData(peaks, barCount);
360
363
  const height = canvas.height;
361
364
  const progressWidth = progress * canvas.width;
@@ -389,7 +392,7 @@ function drawMirror(ctx, canvas, peaks, progress, options) {
389
392
  const dpr = window.devicePixelRatio || 1;
390
393
  const barWidth = options.barWidth * dpr;
391
394
  const barSpacing = options.barSpacing * dpr;
392
- const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
395
+ const barCount = fitBars(canvas, barWidth + barSpacing);
393
396
  const resampledPeaks = resampleData(peaks, barCount);
394
397
  const height = canvas.height;
395
398
  const centerY = height / 2;
@@ -484,7 +487,7 @@ function drawBlocks(ctx, canvas, peaks, progress, options) {
484
487
  const dpr = window.devicePixelRatio || 1;
485
488
  const barWidth = (options.barWidth || 3) * dpr;
486
489
  const barSpacing = (options.barSpacing || 1) * dpr;
487
- const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
490
+ const barCount = fitBars(canvas, barWidth + barSpacing);
488
491
  const resampledPeaks = resampleData(peaks, barCount);
489
492
  const height = canvas.height;
490
493
  const blockSize = 4 * dpr;
@@ -513,7 +516,7 @@ function drawDots(ctx, canvas, peaks, progress, options) {
513
516
  const dpr = window.devicePixelRatio || 1;
514
517
  const barWidth = (options.barWidth || 2) * dpr;
515
518
  const barSpacing = (options.barSpacing || 3) * dpr;
516
- const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
519
+ const barCount = fitBars(canvas, barWidth + barSpacing);
517
520
  const resampledPeaks = resampleData(peaks, barCount);
518
521
  const height = canvas.height;
519
522
  const dotRadius = Math.max(1.5 * dpr, barWidth / 2);
@@ -584,7 +587,7 @@ function detectBPM(buffer) {
584
587
  const channelData = buffer.getChannelData(0);
585
588
  const sampleRate = buffer.sampleRate;
586
589
  const onsets = detectOnsets(channelData, sampleRate);
587
- if (onsets.length < 2) return 120;
590
+ if (onsets.length < 2) return null;
588
591
  const intervals = [];
589
592
  for (let i = 1; i < onsets.length; i++) {
590
593
  intervals.push((onsets[i] - onsets[i - 1]) / sampleRate);
@@ -598,13 +601,14 @@ function detectBPM(buffer) {
598
601
  }
599
602
  });
600
603
  let maxCount = 0;
601
- let detectedBPM = 120;
604
+ let detectedBPM = null;
602
605
  for (const [tempo, count] of Object.entries(tempoGroups)) {
603
606
  if (count > maxCount) {
604
607
  maxCount = count;
605
608
  detectedBPM = parseInt(tempo);
606
609
  }
607
610
  }
611
+ if (detectedBPM === null) return null;
608
612
  if (detectedBPM < 70 && tempoGroups[detectedBPM * 2]) {
609
613
  detectedBPM *= 2;
610
614
  } else if (detectedBPM > 160 && tempoGroups[Math.round(detectedBPM / 2)]) {
@@ -937,7 +941,9 @@ var ENUMS = {
937
941
  var NUMBERS = {
938
942
  height: { min: 1, integer: true },
939
943
  samples: { min: 1, integer: true },
940
- barWidth: { min: 0 },
944
+ // A zero-width bar is invisible anyway, and zero width + zero spacing
945
+ // made the drawers' bar count Infinity (see fitBars in drawing.js).
946
+ barWidth: { min: 0.1 },
941
947
  barSpacing: { min: 0 },
942
948
  barRadius: { min: 0 },
943
949
  bpm: { min: 1 },
@@ -1104,6 +1110,7 @@ var WaveformPlayer = class _WaveformPlayer {
1104
1110
  this.hasError = false;
1105
1111
  this.updateTimer = null;
1106
1112
  this.resizeObserver = null;
1113
+ this._loadId = 0;
1107
1114
  this._ac = new AbortController();
1108
1115
  this.id = this.container.id || generateId(this.options.url);
1109
1116
  _WaveformPlayer.instances.set(this.id, this);
@@ -1115,7 +1122,7 @@ var WaveformPlayer = class _WaveformPlayer {
1115
1122
  this._ac.abort();
1116
1123
  throw error;
1117
1124
  }
1118
- setTimeout(() => {
1125
+ this._readyTimer = setTimeout(() => {
1119
1126
  this._emit("waveformplayer:ready", { player: this, url: this.options.url });
1120
1127
  }, 100);
1121
1128
  }
@@ -1170,8 +1177,9 @@ var WaveformPlayer = class _WaveformPlayer {
1170
1177
  this.bindEvents();
1171
1178
  this.setupResizeObserver();
1172
1179
  requestAnimationFrame(() => {
1180
+ if (this.isDestroying) return;
1173
1181
  this.resizeCanvas();
1174
- if (this.options.url) {
1182
+ if (this.options.url && !this._loadId) {
1175
1183
  this.load(this.options.url).then(() => {
1176
1184
  if (this.options.autoplay) {
1177
1185
  this.play()?.catch(() => {
@@ -1481,7 +1489,7 @@ var WaveformPlayer = class _WaveformPlayer {
1481
1489
  */
1482
1490
  initPlaybackSpeed() {
1483
1491
  if (this.audio && this.options.playbackRate && this.options.playbackRate !== 1) {
1484
- this.audio.playbackRate = this.options.playbackRate;
1492
+ this.audio.playbackRate = this.audio.defaultPlaybackRate = this.options.playbackRate;
1485
1493
  }
1486
1494
  if (this.options.showPlaybackSpeed) {
1487
1495
  this.initSpeedControls();
@@ -1758,6 +1766,7 @@ var WaveformPlayer = class _WaveformPlayer {
1758
1766
  initMediaSession() {
1759
1767
  if (!("mediaSession" in navigator) || !this.options.enableMediaSession) return;
1760
1768
  if (!this.audio) return;
1769
+ _WaveformPlayer._sessionOwner = this;
1761
1770
  this._applyMediaMetadata();
1762
1771
  navigator.mediaSession.setActionHandler("play", () => this.play());
1763
1772
  navigator.mediaSession.setActionHandler("pause", () => this.pause());
@@ -1810,14 +1819,26 @@ var WaveformPlayer = class _WaveformPlayer {
1810
1819
  try {
1811
1820
  if (state === "playing") this.initMediaSession();
1812
1821
  navigator.mediaSession.playbackState = state;
1813
- const d = this.audio.duration;
1814
- if (navigator.mediaSession.setPositionState && d && isFinite(d)) {
1815
- navigator.mediaSession.setPositionState({
1816
- duration: d,
1817
- playbackRate: this.audio.playbackRate || 1,
1818
- position: clamp(this.audio.currentTime, 0, d)
1819
- });
1820
- }
1822
+ this._updatePositionState();
1823
+ } catch (e) {
1824
+ }
1825
+ }
1826
+ /**
1827
+ * Publish duration, rate and position to the lock-screen scrubber. Runs
1828
+ * on play/pause and on the element's `seeked` / `ratechange`, so the
1829
+ * scrubber doesn't drift after a seek or a speed change until the next
1830
+ * play/pause. Only the player that owns the (global) session writes it.
1831
+ * @private
1832
+ */
1833
+ _updatePositionState() {
1834
+ const d = this.audio?.duration;
1835
+ if (_WaveformPlayer._sessionOwner !== this || !navigator.mediaSession?.setPositionState || !(d && isFinite(d))) return;
1836
+ try {
1837
+ navigator.mediaSession.setPositionState({
1838
+ duration: d,
1839
+ playbackRate: this.audio.playbackRate || 1,
1840
+ position: clamp(this.audio.currentTime, 0, d)
1841
+ });
1821
1842
  } catch (e) {
1822
1843
  }
1823
1844
  }
@@ -1843,6 +1864,11 @@ var WaveformPlayer = class _WaveformPlayer {
1843
1864
  this.audio.addEventListener("pause", () => this.onPause());
1844
1865
  this.audio.addEventListener("ended", () => this.onEnded());
1845
1866
  this.audio.addEventListener("error", (e) => this.onError(e));
1867
+ this.audio.addEventListener("seeked", () => this._updatePositionState());
1868
+ this.audio.addEventListener("ratechange", () => this._updatePositionState());
1869
+ this.audio.addEventListener("timeupdate", () => {
1870
+ if (this.isPlaying && Date.now() - this._frameAt > 500) this.updateProgress();
1871
+ });
1846
1872
  }
1847
1873
  this.canvas.addEventListener("click", (e) => this.handleCanvasClick(e));
1848
1874
  this._dragging = false;
@@ -1929,56 +1955,71 @@ var WaveformPlayer = class _WaveformPlayer {
1929
1955
  * accessible name are written *before* the metadata wait, as are peaks
1930
1956
  * supplied via the `waveform` option — none of them need anything from the
1931
1957
  * audio element, and behind the wait they blink in on a slow origin.
1932
- * Without inline peaks the waveform is decoded from the audio instead; a
1933
- * decode failure falls back to a placeholder. The `onLoad` callback fires
1934
- * on success.
1958
+ * Without inline peaks — or when a `.json` peaks sidecar can't be fetched —
1959
+ * the waveform is decoded from the audio instead; a decode failure falls
1960
+ * back to a placeholder. The `onLoad` callback fires on success.
1961
+ *
1962
+ * Every call supersedes the previous one: a load that is overtaken while
1963
+ * it awaits (metadata, a sidecar fetch, the decode) stops there without
1964
+ * touching the player, so a slow first track can't land its peaks, BPM,
1965
+ * error or loading state on the track that replaced it.
1966
+ *
1967
+ * Loading a *different* URL also resets what the previous track left
1968
+ * behind (see {@link WaveformPlayer#_resetTrack}); reloading the same URL
1969
+ * — e.g. a retry after an error — keeps the drawn waveform. Either way the
1970
+ * error state is cleared, so a retry re-enables the player.
1935
1971
  * @param {string} url - Audio URL.
1936
1972
  * @returns {Promise<void>} Resolves once loading settles (errors are caught
1937
1973
  * internally and surfaced through {@link WaveformPlayer#onError}).
1938
1974
  */
1939
1975
  async load(url) {
1976
+ const id = ++this._loadId;
1977
+ const audio = this.audio;
1940
1978
  try {
1979
+ if (url !== this.options.url) this._resetTrack();
1941
1980
  this.setLoading(true);
1942
1981
  this.progress = 0;
1943
- this.hasError = false;
1982
+ this._setError(false);
1944
1983
  this.container.classList.remove("waveform-is-placeholder");
1945
- const hasInlinePeaks = !!this.options.waveform;
1946
- if (hasInlinePeaks) {
1947
- this.setWaveformData(this.options.waveform);
1948
- }
1984
+ this.detectedBPM = null;
1985
+ this.updateBPMDisplay();
1986
+ this.options.url = url;
1987
+ const inlinePeaks = this.options.waveform;
1988
+ const sidecar = inlinePeaks ? this.setWaveformData(inlinePeaks) : null;
1949
1989
  const title = this.options.title || extractTitleFromUrl(url);
1950
1990
  if (this.titleEl) {
1951
1991
  this.titleEl.textContent = title;
1952
1992
  }
1953
1993
  this.applySeekLabel(title);
1954
- if (this.audio) {
1955
- this.audio.src = url;
1956
- if (this.audio.preload !== "none") {
1994
+ if (audio) {
1995
+ audio.src = url;
1996
+ if (audio.preload !== "none") {
1957
1997
  await new Promise((resolve, reject) => {
1958
- const metadataHandler = () => {
1959
- this.audio.removeEventListener("loadedmetadata", metadataHandler);
1960
- this.audio.removeEventListener("error", errorHandler);
1961
- resolve();
1998
+ const settle = (fn) => (e) => {
1999
+ audio.removeEventListener("loadedmetadata", metadataHandler);
2000
+ audio.removeEventListener("error", errorHandler);
2001
+ fn(e);
1962
2002
  };
1963
- const errorHandler = (e) => {
1964
- this.audio.removeEventListener("loadedmetadata", metadataHandler);
1965
- this.audio.removeEventListener("error", errorHandler);
1966
- reject(e);
1967
- };
1968
- this.audio.addEventListener("loadedmetadata", metadataHandler);
1969
- this.audio.addEventListener("error", errorHandler);
2003
+ const metadataHandler = settle(resolve);
2004
+ const errorHandler = settle(reject);
2005
+ audio.addEventListener("loadedmetadata", metadataHandler);
2006
+ audio.addEventListener("error", errorHandler);
1970
2007
  });
1971
2008
  }
1972
2009
  }
1973
- if (!hasInlinePeaks) {
2010
+ const sidecarOk = await sidecar;
2011
+ if (id !== this._loadId) return;
2012
+ if (!inlinePeaks || sidecarOk === false) {
1974
2013
  try {
1975
2014
  const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
2015
+ if (id !== this._loadId) return;
1976
2016
  this.waveformData = result.peaks;
1977
2017
  if (result.bpm) {
1978
2018
  this.detectedBPM = result.bpm;
1979
2019
  this.updateBPMDisplay();
1980
2020
  }
1981
2021
  } catch (error) {
2022
+ if (id !== this._loadId) return;
1982
2023
  console.warn("[WaveformPlayer] Using placeholder waveform:", error);
1983
2024
  this.waveformData = generatePlaceholderWaveform(this.options.samples);
1984
2025
  this.container.classList.add("waveform-is-placeholder");
@@ -1990,11 +2031,43 @@ var WaveformPlayer = class _WaveformPlayer {
1990
2031
  this.options.onLoad(this);
1991
2032
  }
1992
2033
  } catch (error) {
1993
- this.onError(error);
2034
+ if (id === this._loadId && !this.hasError) this.onError(error);
1994
2035
  } finally {
1995
- this.setLoading(false);
2036
+ if (id === this._loadId) this.setLoading(false);
1996
2037
  }
1997
2038
  }
2039
+ /**
2040
+ * Forget everything the previous track left on the player: its peaks,
2041
+ * progress, duration (external mode), time readout and marker buttons.
2042
+ * Shared by {@link WaveformPlayer#loadTrack} and a {@link WaveformPlayer#load}
2043
+ * of a different URL, so neither path can show the old track's `1:30` or
2044
+ * place the new track's markers against the old duration. Per-track
2045
+ * *options* are reset by `loadTrack()`, which is the path that receives them.
2046
+ * @private
2047
+ */
2048
+ _resetTrack() {
2049
+ this.progress = 0;
2050
+ this.waveformData = [];
2051
+ this._extDuration = 0;
2052
+ this._extEnded = false;
2053
+ if (this.currentTimeEl) this.currentTimeEl.textContent = "0:00";
2054
+ if (this.totalTimeEl) this.totalTimeEl.textContent = "0:00";
2055
+ if (this.markersContainer) this.markersContainer.innerHTML = "";
2056
+ }
2057
+ /**
2058
+ * Show or clear the error state: the overlay, the dimmed canvas and the
2059
+ * disabled play button. The one place both {@link WaveformPlayer#onError}
2060
+ * and a fresh {@link WaveformPlayer#load} flip it, so a retry can't leave
2061
+ * half of it behind.
2062
+ * @param {boolean} on - True to enter the error state, false to clear it.
2063
+ * @private
2064
+ */
2065
+ _setError(on) {
2066
+ this.hasError = on;
2067
+ if (this.errorEl) this.errorEl.style.display = on ? "flex" : "none";
2068
+ if (this.canvas) this.canvas.style.opacity = on ? "0.2" : "1";
2069
+ if (this.playBtn) this.playBtn.disabled = on;
2070
+ }
1998
2071
  /**
1999
2072
  * Swap the player to a new track at runtime.
2000
2073
  *
@@ -2002,14 +2075,22 @@ var WaveformPlayer = class _WaveformPlayer {
2002
2075
  * clears error/marker/progress state, merges the new metadata into
2003
2076
  * `this.options`, updates the artist/artwork DOM, then calls
2004
2077
  * {@link WaveformPlayer#load}. Auto-plays the new track unless
2005
- * `options.autoplay === false`.
2078
+ * `options.autoplay === false` — and only if no later `loadTrack()` /
2079
+ * `load()` has superseded this one by the time it finishes loading.
2080
+ *
2081
+ * Per-track options the caller doesn't repeat are reset rather than
2082
+ * inherited from the previous track: `markers`, `waveform`, `bpm` and
2083
+ * `album`.
2006
2084
  * @param {string} url - Audio URL.
2007
2085
  * @param {string|null} [title=null] - Track title; keeps the existing
2008
- * title when null.
2086
+ * title when null. (Deliberate: a controller that only swaps the
2087
+ * audio keeps the label it set. Pass `''` to derive the title from the
2088
+ * URL instead.)
2009
2089
  * @param {string|null} [artist=null] - Track artist; pass `''` to hide
2010
2090
  * the artist row, or null to keep the existing one.
2011
2091
  * @param {Object} [options={}] - Additional options to merge (e.g.
2012
- * `preload`, `artwork`, `artworkAlt`, `markers`, `autoplay`).
2092
+ * `preload`, `artwork`, `artworkAlt`, `markers`, `bpm`, `album`,
2093
+ * `autoplay`).
2013
2094
  * @returns {Promise<void>}
2014
2095
  */
2015
2096
  async loadTrack(url, title = null, artist = null, options = {}) {
@@ -2022,18 +2103,7 @@ var WaveformPlayer = class _WaveformPlayer {
2022
2103
  this.audio.src = "";
2023
2104
  this.audio.load();
2024
2105
  }
2025
- this.hasError = false;
2026
- if (this.errorEl) {
2027
- this.errorEl.style.display = "none";
2028
- }
2029
- if (this.canvas) {
2030
- this.canvas.style.opacity = "1";
2031
- }
2032
- if (this.playBtn) {
2033
- this.playBtn.disabled = false;
2034
- }
2035
- this.progress = 0;
2036
- this.waveformData = [];
2106
+ this._resetTrack();
2037
2107
  this.options = normalizeOptions(mergeOptions(this.options, {
2038
2108
  url,
2039
2109
  title: title === null ? this.options.title : title,
@@ -2048,6 +2118,9 @@ var WaveformPlayer = class _WaveformPlayer {
2048
2118
  } else if (hasArtworkOption) {
2049
2119
  this.options.artworkAlt = this.options.artwork ? DEFAULT_OPTIONS.artworkAlt : "";
2050
2120
  }
2121
+ for (const key of ["bpm", "album"]) {
2122
+ if (options[key] == null) this.options[key] = DEFAULT_OPTIONS[key];
2123
+ }
2051
2124
  if (options.preload && this.audio) {
2052
2125
  this.audio.preload = this.options.preload;
2053
2126
  }
@@ -2065,8 +2138,10 @@ var WaveformPlayer = class _WaveformPlayer {
2065
2138
  }
2066
2139
  this.options.markers = options.markers ? normalizeMarkers(options.markers) : [];
2067
2140
  this.options.waveform = options.waveform || null;
2068
- await this.load(url);
2069
- if (options.autoplay !== false) {
2141
+ const loading = this.load(url);
2142
+ const id = this._loadId;
2143
+ await loading;
2144
+ if (options.autoplay !== false && id === this._loadId) {
2070
2145
  this.play()?.catch(() => {
2071
2146
  });
2072
2147
  }
@@ -2078,26 +2153,51 @@ var WaveformPlayer = class _WaveformPlayer {
2078
2153
  * Normalise externally-supplied waveform data into `this.waveformData` and
2079
2154
  * redraw.
2080
2155
  *
2081
- * Accepts several shapes: a `.json` URL (fetched async; peaks and any
2082
- * embedded `markers` are applied on resolve), a JSON-encoded array string,
2083
- * a comma-separated number string, or a plain number array. Malformed
2084
- * input degrades to an empty array rather than throwing.
2156
+ * Accepts several shapes: a `.json` URL (fetched async — a query string
2157
+ * or fragment is fine, which is what {@link WaveformPlayer.getPeaksUrl}
2158
+ * produces for a versioned audio URL), a JSON-encoded array string, a
2159
+ * comma-separated number string, or a plain number array. Malformed input
2160
+ * degrades to an empty array rather than throwing.
2161
+ *
2162
+ * A sidecar may be a bare peaks array or a `{peaks, markers, bpm}` object
2163
+ * (the shape `@arraypress/waveform-gen` writes): its markers apply when the
2164
+ * track has none of its own, and its `bpm` feeds the badge when no `bpm`
2165
+ * option is set. A sidecar that fails to fetch (network error, non-2xx) or
2166
+ * carries no peaks resolves `false` and leaves the canvas as it was —
2167
+ * {@link WaveformPlayer#load} then decodes the audio instead. One that
2168
+ * resolves after a newer load has started is discarded.
2085
2169
  * @param {string|number[]} data - Peaks as an array, a JSON/CSV string, or
2086
2170
  * a URL to a `.json` peaks file.
2087
- * @private
2171
+ * @returns {Promise<boolean>|undefined} For a `.json` URL, a promise of
2172
+ * whether the sidecar was applied; otherwise `undefined` (applied
2173
+ * synchronously).
2088
2174
  */
2089
2175
  setWaveformData(data) {
2090
- if (typeof data === "string" && data.trim().endsWith(".json")) {
2091
- fetch(data.trim()).then((r) => r.json()).then((json) => {
2092
- this.waveformData = Array.isArray(json) ? json : json.peaks || [];
2176
+ if (typeof data === "string" && /\.json(?:[?#]|$)/i.test(data.trim())) {
2177
+ const id = this._loadId;
2178
+ return fetch(data.trim()).then((r) => {
2179
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
2180
+ return r.json();
2181
+ }).then((json) => {
2182
+ if (id !== this._loadId) return false;
2183
+ const peaks = toNumberArray(Array.isArray(json) ? json : json?.peaks, { fallback: [] });
2184
+ if (!peaks.length) throw new Error("no peaks");
2185
+ this.waveformData = peaks;
2093
2186
  if (json.markers && !this.options.markers?.length) {
2094
2187
  this.options.markers = normalizeMarkers(json.markers);
2095
2188
  this.renderMarkers();
2096
2189
  }
2190
+ const bpm = toFiniteNumber(json.bpm, null, { min: 1 });
2191
+ if (bpm) {
2192
+ this.detectedBPM = bpm;
2193
+ this.updateBPMDisplay();
2194
+ }
2097
2195
  this.drawWaveform();
2098
- }).catch(() => {
2196
+ return true;
2197
+ }).catch((error) => {
2198
+ console.warn("[WaveformPlayer] Could not use peaks file:", data, error);
2199
+ return false;
2099
2200
  });
2100
- return;
2101
2201
  }
2102
2202
  this.waveformData = toNumberArray(data, { fallback: [] });
2103
2203
  this.drawWaveform();
@@ -2121,8 +2221,9 @@ var WaveformPlayer = class _WaveformPlayer {
2121
2221
  /**
2122
2222
  * Re-fit the canvas backing store to its parent's width and the configured
2123
2223
  * height, scaled by the device pixel ratio for crisp rendering, then
2124
- * redraw. Guards against running after destruction.
2125
- * @private
2224
+ * redraw. Guards against running after destruction. Public: the resize
2225
+ * observer doesn't reliably fire on a DOM move, so call this after
2226
+ * relocating the player.
2126
2227
  */
2127
2228
  resizeCanvas() {
2128
2229
  if (!this.canvas || this.isDestroying) {
@@ -2456,8 +2557,8 @@ var WaveformPlayer = class _WaveformPlayer {
2456
2557
  /**
2457
2558
  * `ended` handler (self mode): reset progress and `currentTime` to the
2458
2559
  * start, redraw, reset the time display, dispatch `waveformplayer:ended`
2459
- * (carrying the final time), run {@link WaveformPlayer#onPause}, and fire
2460
- * the `onEnd` callback. No-op during destruction.
2560
+ * (carrying the final time), run {@link WaveformPlayer#onPause} if the
2561
+ * preceding `pause` event hasn't already, and fire the `onEnd` callback. No-op during destruction.
2461
2562
  * @private
2462
2563
  * @fires WaveformPlayer#waveformplayer:ended
2463
2564
  */
@@ -2471,7 +2572,7 @@ var WaveformPlayer = class _WaveformPlayer {
2471
2572
  this.currentTimeEl.textContent = "0:00";
2472
2573
  }
2473
2574
  this._emit("waveformplayer:ended", { player: this, url: this.options.url, currentTime: duration, duration });
2474
- this.onPause();
2575
+ if (this.isPlaying) this.onPause();
2475
2576
  if (this.options.onEnd) {
2476
2577
  this.options.onEnd(this);
2477
2578
  }
@@ -2487,17 +2588,8 @@ var WaveformPlayer = class _WaveformPlayer {
2487
2588
  onError(error) {
2488
2589
  if (this.isDestroying) return;
2489
2590
  console.error("[WaveformPlayer] Audio error:", error);
2490
- this.hasError = true;
2591
+ this._setError(true);
2491
2592
  this.setLoading(false);
2492
- if (this.errorEl) {
2493
- this.errorEl.style.display = "flex";
2494
- }
2495
- if (this.canvas) {
2496
- this.canvas.style.opacity = "0.2";
2497
- }
2498
- if (this.playBtn) {
2499
- this.playBtn.disabled = true;
2500
- }
2501
2593
  if (this.options.onError) {
2502
2594
  this.options.onError(error, this);
2503
2595
  }
@@ -2516,10 +2608,12 @@ var WaveformPlayer = class _WaveformPlayer {
2516
2608
  this.stopSmoothUpdate();
2517
2609
  const update = () => {
2518
2610
  if (this.isPlaying && this.audio && this.audio.duration) {
2611
+ this._frameAt = Date.now();
2519
2612
  this.updateProgress();
2520
2613
  this.updateTimer = requestAnimationFrame(update);
2521
2614
  }
2522
2615
  };
2616
+ this._frameAt = Date.now();
2523
2617
  this.updateTimer = requestAnimationFrame(update);
2524
2618
  }
2525
2619
  /**
@@ -2572,14 +2666,16 @@ var WaveformPlayer = class _WaveformPlayer {
2572
2666
  // UI Updates
2573
2667
  // ============================================
2574
2668
  /**
2575
- * Show the detected BPM in the badge, once a value has been detected.
2669
+ * Show the track's BPM in the badge, or hide the badge when the current
2670
+ * track has none — a load resets the detected value, so the previous
2671
+ * track's tempo can't linger on the next one.
2576
2672
  * @private
2577
2673
  */
2578
2674
  updateBPMDisplay() {
2579
2675
  const bpm = this.options.bpm || this.detectedBPM;
2580
- if (this.bpmEl && this.bpmValueEl && bpm) {
2581
- this.bpmValueEl.textContent = Math.round(bpm);
2582
- this.bpmEl.style.display = "inline-flex";
2676
+ if (this.bpmEl && this.bpmValueEl) {
2677
+ if (bpm) this.bpmValueEl.textContent = Math.round(bpm);
2678
+ this.bpmEl.style.display = bpm ? "inline-flex" : "none";
2583
2679
  }
2584
2680
  }
2585
2681
  /**
@@ -2698,20 +2794,21 @@ var WaveformPlayer = class _WaveformPlayer {
2698
2794
  /**
2699
2795
  * Pause audio.
2700
2796
  *
2701
- * In `audioMode: 'external'`, dispatches `waveformplayer:request-pause`
2702
- * (cancelable) and does NOT touch any audio element. See play().
2797
+ * In `audioMode: 'external'`, dispatches a cancelable
2798
+ * `waveformplayer:request-pause` and does NOT touch any audio element.
2799
+ * Mirrors play(): calling preventDefault() on the event vetoes the pause
2800
+ * as far as the player is concerned — it stays `currentlyPlaying` (the
2801
+ * `singlePlay` bookkeeping). Neither event flips the play/pause visual;
2802
+ * that only changes when the controller calls setPlayingState().
2703
2803
  *
2704
2804
  * @fires WaveformPlayer#waveformplayer:request-pause
2705
2805
  */
2706
2806
  pause() {
2707
- if (_WaveformPlayer.currentlyPlaying === this) {
2807
+ const accepted = this.options.audioMode !== "external" || !this._emit("waveformplayer:request-pause", this._buildTrackDetail(), true).defaultPrevented;
2808
+ if (accepted && _WaveformPlayer.currentlyPlaying === this) {
2708
2809
  _WaveformPlayer.currentlyPlaying = null;
2709
2810
  }
2710
- if (this.options.audioMode === "external") {
2711
- this._emit("waveformplayer:request-pause", this._buildTrackDetail(), true);
2712
- return;
2713
- }
2714
- this.audio.pause();
2811
+ this.audio?.pause();
2715
2812
  }
2716
2813
  /**
2717
2814
  * Build the track detail object dispatched by request-play /
@@ -2771,7 +2868,8 @@ var WaveformPlayer = class _WaveformPlayer {
2771
2868
  * external duration for the accessible slider, dispatches
2772
2869
  * `waveformplayer:timeupdate`, runs `onTimeUpdate`, and synthesizes a
2773
2870
  * one-shot `waveformplayer:ended` (with `onEnd`) when progress reaches the
2774
- * end. No-op for a non-positive duration.
2871
+ * end. No-op for a non-positive duration, and while the user is dragging
2872
+ * the playhead (as in self mode).
2775
2873
  *
2776
2874
  * @param {number} currentTime - Current playback position in seconds.
2777
2875
  * @param {number} duration - Total track duration in seconds.
@@ -2780,13 +2878,13 @@ var WaveformPlayer = class _WaveformPlayer {
2780
2878
  */
2781
2879
  setProgress(currentTime, duration) {
2782
2880
  if (!duration || duration <= 0) return;
2881
+ if (this._dragging) return;
2783
2882
  this.progress = clamp(currentTime / duration);
2784
2883
  if (this.currentTimeEl) this.currentTimeEl.textContent = formatTime(currentTime);
2785
- this._extDuration = duration;
2786
- if (this.totalTimeEl && (!this.totalTimeEl.dataset._extSet || this.totalTimeEl.dataset._extDur !== String(duration))) {
2787
- this.totalTimeEl.textContent = formatTime(duration);
2788
- this.totalTimeEl.dataset._extSet = "1";
2789
- this.totalTimeEl.dataset._extDur = String(duration);
2884
+ if (duration !== this._extDuration) {
2885
+ this._extDuration = duration;
2886
+ if (this.totalTimeEl) this.totalTimeEl.textContent = formatTime(duration);
2887
+ this.renderMarkers();
2790
2888
  }
2791
2889
  this.drawWaveform?.();
2792
2890
  this.updateActiveMarker();
@@ -2818,25 +2916,28 @@ var WaveformPlayer = class _WaveformPlayer {
2818
2916
  /**
2819
2917
  * Seek the owned `<audio>` element to an absolute time, clamped to
2820
2918
  * `[0, duration]`, and refresh progress. Self mode only — a no-op when
2821
- * there is no audio element or duration. External-mode keyboard/click
2822
- * seeks go through {@link WaveformPlayer#seekToSeconds} instead.
2919
+ * there is no audio element or duration, or when `seconds` isn't a finite
2920
+ * number. External-mode keyboard/click seeks go through
2921
+ * {@link WaveformPlayer#seekToSeconds} instead.
2823
2922
  * @param {number} seconds - Target time in seconds.
2824
2923
  */
2825
2924
  seekTo(seconds) {
2826
- if (this.audio && this.audio.duration) {
2827
- this.audio.currentTime = clamp(seconds, 0, this.audio.duration);
2925
+ const s = Number(seconds);
2926
+ if (this.audio && this.audio.duration && Number.isFinite(s)) {
2927
+ this.audio.currentTime = clamp(s, 0, this.audio.duration);
2828
2928
  this.updateProgress();
2829
2929
  }
2830
2930
  }
2831
2931
  /**
2832
2932
  * Seek the owned `<audio>` element to a fraction of the track, clamped to
2833
2933
  * `[0, 1]`, and refresh progress. Self mode only — a no-op without an audio
2834
- * element or duration.
2934
+ * element or duration, or when `percent` isn't a finite number.
2835
2935
  * @param {number} percent - Position as a fraction from 0 to 1.
2836
2936
  */
2837
2937
  seekToPercent(percent) {
2838
- if (this.audio && this.audio.duration) {
2839
- this.audio.currentTime = this.audio.duration * clamp(percent);
2938
+ const p = Number(percent);
2939
+ if (this.audio && this.audio.duration && Number.isFinite(p)) {
2940
+ this.audio.currentTime = this.audio.duration * clamp(p);
2840
2941
  this.updateProgress();
2841
2942
  }
2842
2943
  }
@@ -2859,14 +2960,15 @@ var WaveformPlayer = class _WaveformPlayer {
2859
2960
  * The clamp bounds the range browsers keep audible; the default speed menu
2860
2961
  * offers a narrower 0.5–2, which `playbackRates` can widen up to these
2861
2962
  * bounds. A non-numeric rate is ignored rather than assigned, since
2862
- * `audio.playbackRate = NaN` throws.
2963
+ * `audio.playbackRate = NaN` throws. The rate is also written to
2964
+ * `defaultPlaybackRate`, so it survives the next track load.
2863
2965
  * @param {number} rate - Desired playback rate; clamped to the 0.25–4 range.
2864
2966
  */
2865
2967
  setPlaybackRate(rate) {
2866
2968
  if (!this.audio) return;
2867
2969
  const clampedRate = toFiniteNumber(rate, null, { min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX });
2868
2970
  if (clampedRate === null) return;
2869
- this.audio.playbackRate = clampedRate;
2971
+ this.audio.playbackRate = this.audio.defaultPlaybackRate = clampedRate;
2870
2972
  this.options.playbackRate = clampedRate;
2871
2973
  this.updateSpeedUI();
2872
2974
  }
@@ -2884,9 +2986,10 @@ var WaveformPlayer = class _WaveformPlayer {
2884
2986
  destroy() {
2885
2987
  this.isDestroying = true;
2886
2988
  this._emit("waveformplayer:destroy", { player: this, url: this.options.url });
2887
- this.pause();
2888
2989
  this.stopSmoothUpdate();
2889
2990
  clearTimeout(this._markerLabelTimer);
2991
+ clearTimeout(this._readyTimer);
2992
+ this._loadId++;
2890
2993
  this._ac?.abort();
2891
2994
  if (this.resizeObserver) {
2892
2995
  this.resizeObserver.disconnect();
@@ -2900,6 +3003,9 @@ var WaveformPlayer = class _WaveformPlayer {
2900
3003
  if (_WaveformPlayer.currentlyPlaying === this) {
2901
3004
  _WaveformPlayer.currentlyPlaying = null;
2902
3005
  }
3006
+ if (_WaveformPlayer._sessionOwner === this) {
3007
+ _WaveformPlayer._sessionOwner = null;
3008
+ }
2903
3009
  if (this.audio) {
2904
3010
  this.audio.pause();
2905
3011
  this.audio.src = "";