@arraypress/waveform-player 1.27.1 → 1.28.1

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,57 +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");
1959
+ this.detectedBPM = null;
1960
+ this.updateBPMDisplay();
1920
1961
  this.options.url = url;
1921
- const hasInlinePeaks = !!this.options.waveform;
1922
- if (hasInlinePeaks) {
1923
- this.setWaveformData(this.options.waveform);
1924
- }
1962
+ const inlinePeaks = this.options.waveform;
1963
+ const sidecar = inlinePeaks ? this.setWaveformData(inlinePeaks) : null;
1925
1964
  const title = this.options.title || extractTitleFromUrl(url);
1926
1965
  if (this.titleEl) {
1927
1966
  this.titleEl.textContent = title;
1928
1967
  }
1929
1968
  this.applySeekLabel(title);
1930
- if (this.audio) {
1931
- this.audio.src = url;
1932
- if (this.audio.preload !== "none") {
1969
+ if (audio) {
1970
+ audio.src = url;
1971
+ if (audio.preload !== "none") {
1933
1972
  await new Promise((resolve, reject) => {
1934
- const metadataHandler = () => {
1935
- this.audio.removeEventListener("loadedmetadata", metadataHandler);
1936
- this.audio.removeEventListener("error", errorHandler);
1937
- resolve();
1973
+ const settle = (fn) => (e) => {
1974
+ audio.removeEventListener("loadedmetadata", metadataHandler);
1975
+ audio.removeEventListener("error", errorHandler);
1976
+ fn(e);
1938
1977
  };
1939
- const errorHandler = (e) => {
1940
- this.audio.removeEventListener("loadedmetadata", metadataHandler);
1941
- this.audio.removeEventListener("error", errorHandler);
1942
- reject(e);
1943
- };
1944
- this.audio.addEventListener("loadedmetadata", metadataHandler);
1945
- 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);
1946
1982
  });
1947
1983
  }
1948
1984
  }
1949
- if (!hasInlinePeaks) {
1985
+ const sidecarOk = await sidecar;
1986
+ if (id !== this._loadId) return;
1987
+ if (!inlinePeaks || sidecarOk === false) {
1950
1988
  try {
1951
1989
  const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
1990
+ if (id !== this._loadId) return;
1952
1991
  this.waveformData = result.peaks;
1953
1992
  if (result.bpm) {
1954
1993
  this.detectedBPM = result.bpm;
1955
1994
  this.updateBPMDisplay();
1956
1995
  }
1957
1996
  } catch (error) {
1997
+ if (id !== this._loadId) return;
1958
1998
  console.warn("[WaveformPlayer] Using placeholder waveform:", error);
1959
1999
  this.waveformData = generatePlaceholderWaveform(this.options.samples);
1960
2000
  this.container.classList.add("waveform-is-placeholder");
@@ -1966,11 +2006,43 @@
1966
2006
  this.options.onLoad(this);
1967
2007
  }
1968
2008
  } catch (error) {
1969
- this.onError(error);
2009
+ if (id === this._loadId && !this.hasError) this.onError(error);
1970
2010
  } finally {
1971
- this.setLoading(false);
2011
+ if (id === this._loadId) this.setLoading(false);
1972
2012
  }
1973
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
+ }
1974
2046
  /**
1975
2047
  * Swap the player to a new track at runtime.
1976
2048
  *
@@ -1978,14 +2050,22 @@
1978
2050
  * clears error/marker/progress state, merges the new metadata into
1979
2051
  * `this.options`, updates the artist/artwork DOM, then calls
1980
2052
  * {@link WaveformPlayer#load}. Auto-plays the new track unless
1981
- * `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`.
1982
2059
  * @param {string} url - Audio URL.
1983
2060
  * @param {string|null} [title=null] - Track title; keeps the existing
1984
- * 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.)
1985
2064
  * @param {string|null} [artist=null] - Track artist; pass `''` to hide
1986
2065
  * the artist row, or null to keep the existing one.
1987
2066
  * @param {Object} [options={}] - Additional options to merge (e.g.
1988
- * `preload`, `artwork`, `artworkAlt`, `markers`, `autoplay`).
2067
+ * `preload`, `artwork`, `artworkAlt`, `markers`, `bpm`, `album`,
2068
+ * `autoplay`).
1989
2069
  * @returns {Promise<void>}
1990
2070
  */
1991
2071
  async loadTrack(url, title = null, artist = null, options = {}) {
@@ -1998,18 +2078,7 @@
1998
2078
  this.audio.src = "";
1999
2079
  this.audio.load();
2000
2080
  }
2001
- this.hasError = false;
2002
- if (this.errorEl) {
2003
- this.errorEl.style.display = "none";
2004
- }
2005
- if (this.canvas) {
2006
- this.canvas.style.opacity = "1";
2007
- }
2008
- if (this.playBtn) {
2009
- this.playBtn.disabled = false;
2010
- }
2011
- this.progress = 0;
2012
- this.waveformData = [];
2081
+ this._resetTrack();
2013
2082
  this.options = normalizeOptions(mergeOptions(this.options, {
2014
2083
  url,
2015
2084
  title: title === null ? this.options.title : title,
@@ -2024,6 +2093,9 @@
2024
2093
  } else if (hasArtworkOption) {
2025
2094
  this.options.artworkAlt = this.options.artwork ? DEFAULT_OPTIONS.artworkAlt : "";
2026
2095
  }
2096
+ for (const key of ["bpm", "album"]) {
2097
+ if (options[key] == null) this.options[key] = DEFAULT_OPTIONS[key];
2098
+ }
2027
2099
  if (options.preload && this.audio) {
2028
2100
  this.audio.preload = this.options.preload;
2029
2101
  }
@@ -2041,8 +2113,10 @@
2041
2113
  }
2042
2114
  this.options.markers = options.markers ? normalizeMarkers(options.markers) : [];
2043
2115
  this.options.waveform = options.waveform || null;
2044
- await this.load(url);
2045
- 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) {
2046
2120
  this.play()?.catch(() => {
2047
2121
  });
2048
2122
  }
@@ -2054,26 +2128,51 @@
2054
2128
  * Normalise externally-supplied waveform data into `this.waveformData` and
2055
2129
  * redraw.
2056
2130
  *
2057
- * Accepts several shapes: a `.json` URL (fetched async; peaks and any
2058
- * embedded `markers` are applied on resolve), a JSON-encoded array string,
2059
- * a comma-separated number string, or a plain number array. Malformed
2060
- * 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.
2061
2144
  * @param {string|number[]} data - Peaks as an array, a JSON/CSV string, or
2062
2145
  * a URL to a `.json` peaks file.
2063
- * @private
2146
+ * @returns {Promise<boolean>|undefined} For a `.json` URL, a promise of
2147
+ * whether the sidecar was applied; otherwise `undefined` (applied
2148
+ * synchronously).
2064
2149
  */
2065
2150
  setWaveformData(data) {
2066
- if (typeof data === "string" && data.trim().endsWith(".json")) {
2067
- fetch(data.trim()).then((r) => r.json()).then((json) => {
2068
- 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;
2069
2161
  if (json.markers && !this.options.markers?.length) {
2070
2162
  this.options.markers = normalizeMarkers(json.markers);
2071
2163
  this.renderMarkers();
2072
2164
  }
2165
+ const bpm = toFiniteNumber(json.bpm, null, { min: 1 });
2166
+ if (bpm) {
2167
+ this.detectedBPM = bpm;
2168
+ this.updateBPMDisplay();
2169
+ }
2073
2170
  this.drawWaveform();
2074
- }).catch(() => {
2171
+ return true;
2172
+ }).catch((error) => {
2173
+ console.warn("[WaveformPlayer] Could not use peaks file:", data, error);
2174
+ return false;
2075
2175
  });
2076
- return;
2077
2176
  }
2078
2177
  this.waveformData = toNumberArray(data, { fallback: [] });
2079
2178
  this.drawWaveform();
@@ -2097,8 +2196,9 @@
2097
2196
  /**
2098
2197
  * Re-fit the canvas backing store to its parent's width and the configured
2099
2198
  * height, scaled by the device pixel ratio for crisp rendering, then
2100
- * redraw. Guards against running after destruction.
2101
- * @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.
2102
2202
  */
2103
2203
  resizeCanvas() {
2104
2204
  if (!this.canvas || this.isDestroying) {
@@ -2432,8 +2532,8 @@
2432
2532
  /**
2433
2533
  * `ended` handler (self mode): reset progress and `currentTime` to the
2434
2534
  * start, redraw, reset the time display, dispatch `waveformplayer:ended`
2435
- * (carrying the final time), run {@link WaveformPlayer#onPause}, and fire
2436
- * 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.
2437
2537
  * @private
2438
2538
  * @fires WaveformPlayer#waveformplayer:ended
2439
2539
  */
@@ -2447,7 +2547,7 @@
2447
2547
  this.currentTimeEl.textContent = "0:00";
2448
2548
  }
2449
2549
  this._emit("waveformplayer:ended", { player: this, url: this.options.url, currentTime: duration, duration });
2450
- this.onPause();
2550
+ if (this.isPlaying) this.onPause();
2451
2551
  if (this.options.onEnd) {
2452
2552
  this.options.onEnd(this);
2453
2553
  }
@@ -2463,17 +2563,8 @@
2463
2563
  onError(error) {
2464
2564
  if (this.isDestroying) return;
2465
2565
  console.error("[WaveformPlayer] Audio error:", error);
2466
- this.hasError = true;
2566
+ this._setError(true);
2467
2567
  this.setLoading(false);
2468
- if (this.errorEl) {
2469
- this.errorEl.style.display = "flex";
2470
- }
2471
- if (this.canvas) {
2472
- this.canvas.style.opacity = "0.2";
2473
- }
2474
- if (this.playBtn) {
2475
- this.playBtn.disabled = true;
2476
- }
2477
2568
  if (this.options.onError) {
2478
2569
  this.options.onError(error, this);
2479
2570
  }
@@ -2492,10 +2583,12 @@
2492
2583
  this.stopSmoothUpdate();
2493
2584
  const update = () => {
2494
2585
  if (this.isPlaying && this.audio && this.audio.duration) {
2586
+ this._frameAt = Date.now();
2495
2587
  this.updateProgress();
2496
2588
  this.updateTimer = requestAnimationFrame(update);
2497
2589
  }
2498
2590
  };
2591
+ this._frameAt = Date.now();
2499
2592
  this.updateTimer = requestAnimationFrame(update);
2500
2593
  }
2501
2594
  /**
@@ -2548,14 +2641,16 @@
2548
2641
  // UI Updates
2549
2642
  // ============================================
2550
2643
  /**
2551
- * 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.
2552
2647
  * @private
2553
2648
  */
2554
2649
  updateBPMDisplay() {
2555
2650
  const bpm = this.options.bpm || this.detectedBPM;
2556
- if (this.bpmEl && this.bpmValueEl && bpm) {
2557
- this.bpmValueEl.textContent = Math.round(bpm);
2558
- 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";
2559
2654
  }
2560
2655
  }
2561
2656
  /**
@@ -2674,20 +2769,21 @@
2674
2769
  /**
2675
2770
  * Pause audio.
2676
2771
  *
2677
- * In `audioMode: 'external'`, dispatches `waveformplayer:request-pause`
2678
- * (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().
2679
2778
  *
2680
2779
  * @fires WaveformPlayer#waveformplayer:request-pause
2681
2780
  */
2682
2781
  pause() {
2683
- 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) {
2684
2784
  _WaveformPlayer.currentlyPlaying = null;
2685
2785
  }
2686
- if (this.options.audioMode === "external") {
2687
- this._emit("waveformplayer:request-pause", this._buildTrackDetail(), true);
2688
- return;
2689
- }
2690
- this.audio.pause();
2786
+ this.audio?.pause();
2691
2787
  }
2692
2788
  /**
2693
2789
  * Build the track detail object dispatched by request-play /
@@ -2747,7 +2843,8 @@
2747
2843
  * external duration for the accessible slider, dispatches
2748
2844
  * `waveformplayer:timeupdate`, runs `onTimeUpdate`, and synthesizes a
2749
2845
  * one-shot `waveformplayer:ended` (with `onEnd`) when progress reaches the
2750
- * 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).
2751
2848
  *
2752
2849
  * @param {number} currentTime - Current playback position in seconds.
2753
2850
  * @param {number} duration - Total track duration in seconds.
@@ -2756,13 +2853,13 @@
2756
2853
  */
2757
2854
  setProgress(currentTime, duration) {
2758
2855
  if (!duration || duration <= 0) return;
2856
+ if (this._dragging) return;
2759
2857
  this.progress = clamp(currentTime / duration);
2760
2858
  if (this.currentTimeEl) this.currentTimeEl.textContent = formatTime(currentTime);
2761
- this._extDuration = duration;
2762
- if (this.totalTimeEl && (!this.totalTimeEl.dataset._extSet || this.totalTimeEl.dataset._extDur !== String(duration))) {
2763
- this.totalTimeEl.textContent = formatTime(duration);
2764
- this.totalTimeEl.dataset._extSet = "1";
2765
- 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();
2766
2863
  }
2767
2864
  this.drawWaveform?.();
2768
2865
  this.updateActiveMarker();
@@ -2794,25 +2891,28 @@
2794
2891
  /**
2795
2892
  * Seek the owned `<audio>` element to an absolute time, clamped to
2796
2893
  * `[0, duration]`, and refresh progress. Self mode only — a no-op when
2797
- * there is no audio element or duration. External-mode keyboard/click
2798
- * 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.
2799
2897
  * @param {number} seconds - Target time in seconds.
2800
2898
  */
2801
2899
  seekTo(seconds) {
2802
- if (this.audio && this.audio.duration) {
2803
- 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);
2804
2903
  this.updateProgress();
2805
2904
  }
2806
2905
  }
2807
2906
  /**
2808
2907
  * Seek the owned `<audio>` element to a fraction of the track, clamped to
2809
2908
  * `[0, 1]`, and refresh progress. Self mode only — a no-op without an audio
2810
- * element or duration.
2909
+ * element or duration, or when `percent` isn't a finite number.
2811
2910
  * @param {number} percent - Position as a fraction from 0 to 1.
2812
2911
  */
2813
2912
  seekToPercent(percent) {
2814
- if (this.audio && this.audio.duration) {
2815
- 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);
2816
2916
  this.updateProgress();
2817
2917
  }
2818
2918
  }
@@ -2835,14 +2935,15 @@
2835
2935
  * The clamp bounds the range browsers keep audible; the default speed menu
2836
2936
  * offers a narrower 0.5–2, which `playbackRates` can widen up to these
2837
2937
  * bounds. A non-numeric rate is ignored rather than assigned, since
2838
- * `audio.playbackRate = NaN` throws.
2938
+ * `audio.playbackRate = NaN` throws. The rate is also written to
2939
+ * `defaultPlaybackRate`, so it survives the next track load.
2839
2940
  * @param {number} rate - Desired playback rate; clamped to the 0.25–4 range.
2840
2941
  */
2841
2942
  setPlaybackRate(rate) {
2842
2943
  if (!this.audio) return;
2843
2944
  const clampedRate = toFiniteNumber(rate, null, { min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX });
2844
2945
  if (clampedRate === null) return;
2845
- this.audio.playbackRate = clampedRate;
2946
+ this.audio.playbackRate = this.audio.defaultPlaybackRate = clampedRate;
2846
2947
  this.options.playbackRate = clampedRate;
2847
2948
  this.updateSpeedUI();
2848
2949
  }
@@ -2860,9 +2961,10 @@
2860
2961
  destroy() {
2861
2962
  this.isDestroying = true;
2862
2963
  this._emit("waveformplayer:destroy", { player: this, url: this.options.url });
2863
- this.pause();
2864
2964
  this.stopSmoothUpdate();
2865
2965
  clearTimeout(this._markerLabelTimer);
2966
+ clearTimeout(this._readyTimer);
2967
+ this._loadId++;
2866
2968
  this._ac?.abort();
2867
2969
  if (this.resizeObserver) {
2868
2970
  this.resizeObserver.disconnect();
@@ -2876,6 +2978,9 @@
2876
2978
  if (_WaveformPlayer.currentlyPlaying === this) {
2877
2979
  _WaveformPlayer.currentlyPlaying = null;
2878
2980
  }
2981
+ if (_WaveformPlayer._sessionOwner === this) {
2982
+ _WaveformPlayer._sessionOwner = null;
2983
+ }
2879
2984
  if (this.audio) {
2880
2985
  this.audio.pause();
2881
2986
  this.audio.src = "";