@arraypress/waveform-player 1.27.1 → 1.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/waveform-player-no-autoinit.cjs +220 -115
- package/dist/waveform-player-no-autoinit.esm.js +5 -5
- package/dist/waveform-player.cjs +220 -115
- package/dist/waveform-player.esm.js +5 -5
- package/dist/waveform-player.js +220 -115
- package/dist/waveform-player.min.js +5 -5
- package/index.d.ts +43 -12
- package/package.json +1 -1
- package/src/js/bpm.js +11 -5
- package/src/js/core.js +286 -124
- package/src/js/drawing.js +19 -4
- package/src/js/themes.js +3 -1
- package/src/js/utils.js +6 -4
|
@@ -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 =
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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
|
|
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 =
|
|
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
|
-
|
|
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
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
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,57 +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
|
|
1933
|
-
*
|
|
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.
|
|
1982
|
+
this._setError(false);
|
|
1944
1983
|
this.container.classList.remove("waveform-is-placeholder");
|
|
1984
|
+
this.detectedBPM = null;
|
|
1985
|
+
this.updateBPMDisplay();
|
|
1945
1986
|
this.options.url = url;
|
|
1946
|
-
const
|
|
1947
|
-
|
|
1948
|
-
this.setWaveformData(this.options.waveform);
|
|
1949
|
-
}
|
|
1987
|
+
const inlinePeaks = this.options.waveform;
|
|
1988
|
+
const sidecar = inlinePeaks ? this.setWaveformData(inlinePeaks) : null;
|
|
1950
1989
|
const title = this.options.title || extractTitleFromUrl(url);
|
|
1951
1990
|
if (this.titleEl) {
|
|
1952
1991
|
this.titleEl.textContent = title;
|
|
1953
1992
|
}
|
|
1954
1993
|
this.applySeekLabel(title);
|
|
1955
|
-
if (
|
|
1956
|
-
|
|
1957
|
-
if (
|
|
1994
|
+
if (audio) {
|
|
1995
|
+
audio.src = url;
|
|
1996
|
+
if (audio.preload !== "none") {
|
|
1958
1997
|
await new Promise((resolve, reject) => {
|
|
1959
|
-
const
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1998
|
+
const settle = (fn) => (e) => {
|
|
1999
|
+
audio.removeEventListener("loadedmetadata", metadataHandler);
|
|
2000
|
+
audio.removeEventListener("error", errorHandler);
|
|
2001
|
+
fn(e);
|
|
1963
2002
|
};
|
|
1964
|
-
const
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
};
|
|
1969
|
-
this.audio.addEventListener("loadedmetadata", metadataHandler);
|
|
1970
|
-
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);
|
|
1971
2007
|
});
|
|
1972
2008
|
}
|
|
1973
2009
|
}
|
|
1974
|
-
|
|
2010
|
+
const sidecarOk = await sidecar;
|
|
2011
|
+
if (id !== this._loadId) return;
|
|
2012
|
+
if (!inlinePeaks || sidecarOk === false) {
|
|
1975
2013
|
try {
|
|
1976
2014
|
const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
|
|
2015
|
+
if (id !== this._loadId) return;
|
|
1977
2016
|
this.waveformData = result.peaks;
|
|
1978
2017
|
if (result.bpm) {
|
|
1979
2018
|
this.detectedBPM = result.bpm;
|
|
1980
2019
|
this.updateBPMDisplay();
|
|
1981
2020
|
}
|
|
1982
2021
|
} catch (error) {
|
|
2022
|
+
if (id !== this._loadId) return;
|
|
1983
2023
|
console.warn("[WaveformPlayer] Using placeholder waveform:", error);
|
|
1984
2024
|
this.waveformData = generatePlaceholderWaveform(this.options.samples);
|
|
1985
2025
|
this.container.classList.add("waveform-is-placeholder");
|
|
@@ -1991,11 +2031,43 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
1991
2031
|
this.options.onLoad(this);
|
|
1992
2032
|
}
|
|
1993
2033
|
} catch (error) {
|
|
1994
|
-
this.onError(error);
|
|
2034
|
+
if (id === this._loadId && !this.hasError) this.onError(error);
|
|
1995
2035
|
} finally {
|
|
1996
|
-
this.setLoading(false);
|
|
2036
|
+
if (id === this._loadId) this.setLoading(false);
|
|
1997
2037
|
}
|
|
1998
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
|
+
}
|
|
1999
2071
|
/**
|
|
2000
2072
|
* Swap the player to a new track at runtime.
|
|
2001
2073
|
*
|
|
@@ -2003,14 +2075,22 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2003
2075
|
* clears error/marker/progress state, merges the new metadata into
|
|
2004
2076
|
* `this.options`, updates the artist/artwork DOM, then calls
|
|
2005
2077
|
* {@link WaveformPlayer#load}. Auto-plays the new track unless
|
|
2006
|
-
* `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`.
|
|
2007
2084
|
* @param {string} url - Audio URL.
|
|
2008
2085
|
* @param {string|null} [title=null] - Track title; keeps the existing
|
|
2009
|
-
* 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.)
|
|
2010
2089
|
* @param {string|null} [artist=null] - Track artist; pass `''` to hide
|
|
2011
2090
|
* the artist row, or null to keep the existing one.
|
|
2012
2091
|
* @param {Object} [options={}] - Additional options to merge (e.g.
|
|
2013
|
-
* `preload`, `artwork`, `artworkAlt`, `markers`, `
|
|
2092
|
+
* `preload`, `artwork`, `artworkAlt`, `markers`, `bpm`, `album`,
|
|
2093
|
+
* `autoplay`).
|
|
2014
2094
|
* @returns {Promise<void>}
|
|
2015
2095
|
*/
|
|
2016
2096
|
async loadTrack(url, title = null, artist = null, options = {}) {
|
|
@@ -2023,18 +2103,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2023
2103
|
this.audio.src = "";
|
|
2024
2104
|
this.audio.load();
|
|
2025
2105
|
}
|
|
2026
|
-
this.
|
|
2027
|
-
if (this.errorEl) {
|
|
2028
|
-
this.errorEl.style.display = "none";
|
|
2029
|
-
}
|
|
2030
|
-
if (this.canvas) {
|
|
2031
|
-
this.canvas.style.opacity = "1";
|
|
2032
|
-
}
|
|
2033
|
-
if (this.playBtn) {
|
|
2034
|
-
this.playBtn.disabled = false;
|
|
2035
|
-
}
|
|
2036
|
-
this.progress = 0;
|
|
2037
|
-
this.waveformData = [];
|
|
2106
|
+
this._resetTrack();
|
|
2038
2107
|
this.options = normalizeOptions(mergeOptions(this.options, {
|
|
2039
2108
|
url,
|
|
2040
2109
|
title: title === null ? this.options.title : title,
|
|
@@ -2049,6 +2118,9 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2049
2118
|
} else if (hasArtworkOption) {
|
|
2050
2119
|
this.options.artworkAlt = this.options.artwork ? DEFAULT_OPTIONS.artworkAlt : "";
|
|
2051
2120
|
}
|
|
2121
|
+
for (const key of ["bpm", "album"]) {
|
|
2122
|
+
if (options[key] == null) this.options[key] = DEFAULT_OPTIONS[key];
|
|
2123
|
+
}
|
|
2052
2124
|
if (options.preload && this.audio) {
|
|
2053
2125
|
this.audio.preload = this.options.preload;
|
|
2054
2126
|
}
|
|
@@ -2066,8 +2138,10 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2066
2138
|
}
|
|
2067
2139
|
this.options.markers = options.markers ? normalizeMarkers(options.markers) : [];
|
|
2068
2140
|
this.options.waveform = options.waveform || null;
|
|
2069
|
-
|
|
2070
|
-
|
|
2141
|
+
const loading = this.load(url);
|
|
2142
|
+
const id = this._loadId;
|
|
2143
|
+
await loading;
|
|
2144
|
+
if (options.autoplay !== false && id === this._loadId) {
|
|
2071
2145
|
this.play()?.catch(() => {
|
|
2072
2146
|
});
|
|
2073
2147
|
}
|
|
@@ -2079,26 +2153,51 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2079
2153
|
* Normalise externally-supplied waveform data into `this.waveformData` and
|
|
2080
2154
|
* redraw.
|
|
2081
2155
|
*
|
|
2082
|
-
* Accepts several shapes: a `.json` URL (fetched async
|
|
2083
|
-
*
|
|
2084
|
-
* a
|
|
2085
|
-
*
|
|
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.
|
|
2086
2169
|
* @param {string|number[]} data - Peaks as an array, a JSON/CSV string, or
|
|
2087
2170
|
* a URL to a `.json` peaks file.
|
|
2088
|
-
* @
|
|
2171
|
+
* @returns {Promise<boolean>|undefined} For a `.json` URL, a promise of
|
|
2172
|
+
* whether the sidecar was applied; otherwise `undefined` (applied
|
|
2173
|
+
* synchronously).
|
|
2089
2174
|
*/
|
|
2090
2175
|
setWaveformData(data) {
|
|
2091
|
-
if (typeof data === "string" &&
|
|
2092
|
-
|
|
2093
|
-
|
|
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;
|
|
2094
2186
|
if (json.markers && !this.options.markers?.length) {
|
|
2095
2187
|
this.options.markers = normalizeMarkers(json.markers);
|
|
2096
2188
|
this.renderMarkers();
|
|
2097
2189
|
}
|
|
2190
|
+
const bpm = toFiniteNumber(json.bpm, null, { min: 1 });
|
|
2191
|
+
if (bpm) {
|
|
2192
|
+
this.detectedBPM = bpm;
|
|
2193
|
+
this.updateBPMDisplay();
|
|
2194
|
+
}
|
|
2098
2195
|
this.drawWaveform();
|
|
2099
|
-
|
|
2196
|
+
return true;
|
|
2197
|
+
}).catch((error) => {
|
|
2198
|
+
console.warn("[WaveformPlayer] Could not use peaks file:", data, error);
|
|
2199
|
+
return false;
|
|
2100
2200
|
});
|
|
2101
|
-
return;
|
|
2102
2201
|
}
|
|
2103
2202
|
this.waveformData = toNumberArray(data, { fallback: [] });
|
|
2104
2203
|
this.drawWaveform();
|
|
@@ -2122,8 +2221,9 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2122
2221
|
/**
|
|
2123
2222
|
* Re-fit the canvas backing store to its parent's width and the configured
|
|
2124
2223
|
* height, scaled by the device pixel ratio for crisp rendering, then
|
|
2125
|
-
* redraw. Guards against running after destruction.
|
|
2126
|
-
*
|
|
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.
|
|
2127
2227
|
*/
|
|
2128
2228
|
resizeCanvas() {
|
|
2129
2229
|
if (!this.canvas || this.isDestroying) {
|
|
@@ -2457,8 +2557,8 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2457
2557
|
/**
|
|
2458
2558
|
* `ended` handler (self mode): reset progress and `currentTime` to the
|
|
2459
2559
|
* start, redraw, reset the time display, dispatch `waveformplayer:ended`
|
|
2460
|
-
* (carrying the final time), run {@link WaveformPlayer#onPause}
|
|
2461
|
-
* 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.
|
|
2462
2562
|
* @private
|
|
2463
2563
|
* @fires WaveformPlayer#waveformplayer:ended
|
|
2464
2564
|
*/
|
|
@@ -2472,7 +2572,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2472
2572
|
this.currentTimeEl.textContent = "0:00";
|
|
2473
2573
|
}
|
|
2474
2574
|
this._emit("waveformplayer:ended", { player: this, url: this.options.url, currentTime: duration, duration });
|
|
2475
|
-
this.onPause();
|
|
2575
|
+
if (this.isPlaying) this.onPause();
|
|
2476
2576
|
if (this.options.onEnd) {
|
|
2477
2577
|
this.options.onEnd(this);
|
|
2478
2578
|
}
|
|
@@ -2488,17 +2588,8 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2488
2588
|
onError(error) {
|
|
2489
2589
|
if (this.isDestroying) return;
|
|
2490
2590
|
console.error("[WaveformPlayer] Audio error:", error);
|
|
2491
|
-
this.
|
|
2591
|
+
this._setError(true);
|
|
2492
2592
|
this.setLoading(false);
|
|
2493
|
-
if (this.errorEl) {
|
|
2494
|
-
this.errorEl.style.display = "flex";
|
|
2495
|
-
}
|
|
2496
|
-
if (this.canvas) {
|
|
2497
|
-
this.canvas.style.opacity = "0.2";
|
|
2498
|
-
}
|
|
2499
|
-
if (this.playBtn) {
|
|
2500
|
-
this.playBtn.disabled = true;
|
|
2501
|
-
}
|
|
2502
2593
|
if (this.options.onError) {
|
|
2503
2594
|
this.options.onError(error, this);
|
|
2504
2595
|
}
|
|
@@ -2517,10 +2608,12 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2517
2608
|
this.stopSmoothUpdate();
|
|
2518
2609
|
const update = () => {
|
|
2519
2610
|
if (this.isPlaying && this.audio && this.audio.duration) {
|
|
2611
|
+
this._frameAt = Date.now();
|
|
2520
2612
|
this.updateProgress();
|
|
2521
2613
|
this.updateTimer = requestAnimationFrame(update);
|
|
2522
2614
|
}
|
|
2523
2615
|
};
|
|
2616
|
+
this._frameAt = Date.now();
|
|
2524
2617
|
this.updateTimer = requestAnimationFrame(update);
|
|
2525
2618
|
}
|
|
2526
2619
|
/**
|
|
@@ -2573,14 +2666,16 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2573
2666
|
// UI Updates
|
|
2574
2667
|
// ============================================
|
|
2575
2668
|
/**
|
|
2576
|
-
* Show the
|
|
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.
|
|
2577
2672
|
* @private
|
|
2578
2673
|
*/
|
|
2579
2674
|
updateBPMDisplay() {
|
|
2580
2675
|
const bpm = this.options.bpm || this.detectedBPM;
|
|
2581
|
-
if (this.bpmEl && this.bpmValueEl
|
|
2582
|
-
this.bpmValueEl.textContent = Math.round(bpm);
|
|
2583
|
-
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";
|
|
2584
2679
|
}
|
|
2585
2680
|
}
|
|
2586
2681
|
/**
|
|
@@ -2699,20 +2794,21 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2699
2794
|
/**
|
|
2700
2795
|
* Pause audio.
|
|
2701
2796
|
*
|
|
2702
|
-
* In `audioMode: 'external'`, dispatches
|
|
2703
|
-
*
|
|
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().
|
|
2704
2803
|
*
|
|
2705
2804
|
* @fires WaveformPlayer#waveformplayer:request-pause
|
|
2706
2805
|
*/
|
|
2707
2806
|
pause() {
|
|
2708
|
-
|
|
2807
|
+
const accepted = this.options.audioMode !== "external" || !this._emit("waveformplayer:request-pause", this._buildTrackDetail(), true).defaultPrevented;
|
|
2808
|
+
if (accepted && _WaveformPlayer.currentlyPlaying === this) {
|
|
2709
2809
|
_WaveformPlayer.currentlyPlaying = null;
|
|
2710
2810
|
}
|
|
2711
|
-
|
|
2712
|
-
this._emit("waveformplayer:request-pause", this._buildTrackDetail(), true);
|
|
2713
|
-
return;
|
|
2714
|
-
}
|
|
2715
|
-
this.audio.pause();
|
|
2811
|
+
this.audio?.pause();
|
|
2716
2812
|
}
|
|
2717
2813
|
/**
|
|
2718
2814
|
* Build the track detail object dispatched by request-play /
|
|
@@ -2772,7 +2868,8 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2772
2868
|
* external duration for the accessible slider, dispatches
|
|
2773
2869
|
* `waveformplayer:timeupdate`, runs `onTimeUpdate`, and synthesizes a
|
|
2774
2870
|
* one-shot `waveformplayer:ended` (with `onEnd`) when progress reaches the
|
|
2775
|
-
* 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).
|
|
2776
2873
|
*
|
|
2777
2874
|
* @param {number} currentTime - Current playback position in seconds.
|
|
2778
2875
|
* @param {number} duration - Total track duration in seconds.
|
|
@@ -2781,13 +2878,13 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2781
2878
|
*/
|
|
2782
2879
|
setProgress(currentTime, duration) {
|
|
2783
2880
|
if (!duration || duration <= 0) return;
|
|
2881
|
+
if (this._dragging) return;
|
|
2784
2882
|
this.progress = clamp(currentTime / duration);
|
|
2785
2883
|
if (this.currentTimeEl) this.currentTimeEl.textContent = formatTime(currentTime);
|
|
2786
|
-
this._extDuration
|
|
2787
|
-
|
|
2788
|
-
this.totalTimeEl.textContent = formatTime(duration);
|
|
2789
|
-
this.
|
|
2790
|
-
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();
|
|
2791
2888
|
}
|
|
2792
2889
|
this.drawWaveform?.();
|
|
2793
2890
|
this.updateActiveMarker();
|
|
@@ -2819,25 +2916,28 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2819
2916
|
/**
|
|
2820
2917
|
* Seek the owned `<audio>` element to an absolute time, clamped to
|
|
2821
2918
|
* `[0, duration]`, and refresh progress. Self mode only — a no-op when
|
|
2822
|
-
* there is no audio element or duration
|
|
2823
|
-
* seeks go through
|
|
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.
|
|
2824
2922
|
* @param {number} seconds - Target time in seconds.
|
|
2825
2923
|
*/
|
|
2826
2924
|
seekTo(seconds) {
|
|
2827
|
-
|
|
2828
|
-
|
|
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);
|
|
2829
2928
|
this.updateProgress();
|
|
2830
2929
|
}
|
|
2831
2930
|
}
|
|
2832
2931
|
/**
|
|
2833
2932
|
* Seek the owned `<audio>` element to a fraction of the track, clamped to
|
|
2834
2933
|
* `[0, 1]`, and refresh progress. Self mode only — a no-op without an audio
|
|
2835
|
-
* element or duration.
|
|
2934
|
+
* element or duration, or when `percent` isn't a finite number.
|
|
2836
2935
|
* @param {number} percent - Position as a fraction from 0 to 1.
|
|
2837
2936
|
*/
|
|
2838
2937
|
seekToPercent(percent) {
|
|
2839
|
-
|
|
2840
|
-
|
|
2938
|
+
const p = Number(percent);
|
|
2939
|
+
if (this.audio && this.audio.duration && Number.isFinite(p)) {
|
|
2940
|
+
this.audio.currentTime = this.audio.duration * clamp(p);
|
|
2841
2941
|
this.updateProgress();
|
|
2842
2942
|
}
|
|
2843
2943
|
}
|
|
@@ -2860,14 +2960,15 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2860
2960
|
* The clamp bounds the range browsers keep audible; the default speed menu
|
|
2861
2961
|
* offers a narrower 0.5–2, which `playbackRates` can widen up to these
|
|
2862
2962
|
* bounds. A non-numeric rate is ignored rather than assigned, since
|
|
2863
|
-
* `audio.playbackRate = NaN` throws.
|
|
2963
|
+
* `audio.playbackRate = NaN` throws. The rate is also written to
|
|
2964
|
+
* `defaultPlaybackRate`, so it survives the next track load.
|
|
2864
2965
|
* @param {number} rate - Desired playback rate; clamped to the 0.25–4 range.
|
|
2865
2966
|
*/
|
|
2866
2967
|
setPlaybackRate(rate) {
|
|
2867
2968
|
if (!this.audio) return;
|
|
2868
2969
|
const clampedRate = toFiniteNumber(rate, null, { min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX });
|
|
2869
2970
|
if (clampedRate === null) return;
|
|
2870
|
-
this.audio.playbackRate = clampedRate;
|
|
2971
|
+
this.audio.playbackRate = this.audio.defaultPlaybackRate = clampedRate;
|
|
2871
2972
|
this.options.playbackRate = clampedRate;
|
|
2872
2973
|
this.updateSpeedUI();
|
|
2873
2974
|
}
|
|
@@ -2885,9 +2986,10 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2885
2986
|
destroy() {
|
|
2886
2987
|
this.isDestroying = true;
|
|
2887
2988
|
this._emit("waveformplayer:destroy", { player: this, url: this.options.url });
|
|
2888
|
-
this.pause();
|
|
2889
2989
|
this.stopSmoothUpdate();
|
|
2890
2990
|
clearTimeout(this._markerLabelTimer);
|
|
2991
|
+
clearTimeout(this._readyTimer);
|
|
2992
|
+
this._loadId++;
|
|
2891
2993
|
this._ac?.abort();
|
|
2892
2994
|
if (this.resizeObserver) {
|
|
2893
2995
|
this.resizeObserver.disconnect();
|
|
@@ -2901,6 +3003,9 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2901
3003
|
if (_WaveformPlayer.currentlyPlaying === this) {
|
|
2902
3004
|
_WaveformPlayer.currentlyPlaying = null;
|
|
2903
3005
|
}
|
|
3006
|
+
if (_WaveformPlayer._sessionOwner === this) {
|
|
3007
|
+
_WaveformPlayer._sessionOwner = null;
|
|
3008
|
+
}
|
|
2904
3009
|
if (this.audio) {
|
|
2905
3010
|
this.audio.pause();
|
|
2906
3011
|
this.audio.src = "";
|