@arraypress/waveform-player 1.26.0 → 1.27.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/README.md +12 -0
- package/dist/waveform-player-no-autoinit.cjs +3041 -0
- package/dist/waveform-player-no-autoinit.esm.js +64 -0
- package/dist/waveform-player.cjs +16 -11
- package/dist/waveform-player.esm.js +2 -2
- package/dist/waveform-player.js +15 -10
- package/dist/waveform-player.min.js +2 -2
- package/no-autoinit.d.ts +17 -0
- package/package.json +17 -3
- package/src/js/entry.js +143 -0
- package/src/js/index.js +34 -121
- package/src/js/utils.js +17 -0
|
@@ -0,0 +1,3041 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
|
|
19
|
+
// src/js/entry.js
|
|
20
|
+
var entry_exports = {};
|
|
21
|
+
__export(entry_exports, {
|
|
22
|
+
WaveformPlayer: () => WaveformPlayer,
|
|
23
|
+
default: () => entry_default
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(entry_exports);
|
|
26
|
+
|
|
27
|
+
// src/js/utils.js
|
|
28
|
+
var DEFAULT_SAMPLES = 1800;
|
|
29
|
+
function isBrowser() {
|
|
30
|
+
return typeof window !== "undefined" && typeof document !== "undefined";
|
|
31
|
+
}
|
|
32
|
+
function maxOf(values) {
|
|
33
|
+
let max = -Infinity;
|
|
34
|
+
for (let i = 0; i < values.length; i++) {
|
|
35
|
+
if (values[i] > max) max = values[i];
|
|
36
|
+
}
|
|
37
|
+
return max;
|
|
38
|
+
}
|
|
39
|
+
function escapeHtml(str) {
|
|
40
|
+
return String(str == null ? "" : str).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
41
|
+
}
|
|
42
|
+
function formatCssLength(value) {
|
|
43
|
+
return escapeHtml(typeof value === "number" ? `${value}px` : value);
|
|
44
|
+
}
|
|
45
|
+
function isSafeHref(url) {
|
|
46
|
+
if (typeof url !== "string" || url === "") return false;
|
|
47
|
+
try {
|
|
48
|
+
const u = new URL(url, "http://localhost/");
|
|
49
|
+
return u.protocol === "http:" || u.protocol === "https:";
|
|
50
|
+
} catch (e) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function clamp(value, min = 0, max = 1) {
|
|
55
|
+
return Math.max(min, Math.min(value, max));
|
|
56
|
+
}
|
|
57
|
+
function toFiniteNumber(value, fallback = null, opts = {}) {
|
|
58
|
+
const { min = -Infinity, max = Infinity, integer = false } = opts;
|
|
59
|
+
const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
|
|
60
|
+
if (!Number.isFinite(n)) return fallback;
|
|
61
|
+
const bounded = clamp(n, min, max);
|
|
62
|
+
return integer ? Math.round(bounded) : bounded;
|
|
63
|
+
}
|
|
64
|
+
function toArray(value, fallback = null) {
|
|
65
|
+
if (Array.isArray(value)) return value;
|
|
66
|
+
if (typeof value === "string" && value.trim().startsWith("[")) {
|
|
67
|
+
try {
|
|
68
|
+
const parsed = JSON.parse(value);
|
|
69
|
+
if (Array.isArray(parsed)) return parsed;
|
|
70
|
+
} catch (e) {
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return fallback;
|
|
74
|
+
}
|
|
75
|
+
function toNumberArray(value, opts = {}) {
|
|
76
|
+
const { min = -Infinity, max = Infinity, fallback = null } = opts;
|
|
77
|
+
let list = toArray(value);
|
|
78
|
+
if (!list && typeof value === "string" && value.trim() !== "") {
|
|
79
|
+
list = value.split(/[,\s]+/);
|
|
80
|
+
}
|
|
81
|
+
if (!list) return fallback;
|
|
82
|
+
const numbers = list.map((v) => toFiniteNumber(v)).filter((n) => n !== null && n >= min && n <= max);
|
|
83
|
+
return numbers.length ? numbers : fallback;
|
|
84
|
+
}
|
|
85
|
+
function toEnum(value, allowed, fallback = null) {
|
|
86
|
+
return allowed.includes(value) ? value : fallback;
|
|
87
|
+
}
|
|
88
|
+
function toBool(value) {
|
|
89
|
+
if (typeof value === "string") {
|
|
90
|
+
const v = value.trim().toLowerCase();
|
|
91
|
+
return v !== "" && v !== "false" && v !== "0";
|
|
92
|
+
}
|
|
93
|
+
return !!value;
|
|
94
|
+
}
|
|
95
|
+
function parseBoolAttr(value) {
|
|
96
|
+
return value === void 0 ? void 0 : value === "true";
|
|
97
|
+
}
|
|
98
|
+
function parseColorValue(value) {
|
|
99
|
+
if (typeof value === "string" && value.trim().startsWith("[")) {
|
|
100
|
+
try {
|
|
101
|
+
return JSON.parse(value);
|
|
102
|
+
} catch (e) {
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return value;
|
|
106
|
+
}
|
|
107
|
+
function parseDataAttributes(element) {
|
|
108
|
+
const options = {};
|
|
109
|
+
const setBool = (optKey, dataKey = optKey) => {
|
|
110
|
+
const v = parseBoolAttr(element.dataset[dataKey]);
|
|
111
|
+
if (v !== void 0) options[optKey] = v;
|
|
112
|
+
};
|
|
113
|
+
const setNum = (optKey, dataKey = optKey, float = false) => {
|
|
114
|
+
const raw = element.dataset[dataKey];
|
|
115
|
+
if (raw) options[optKey] = float ? parseFloat(raw) : parseInt(raw, 10);
|
|
116
|
+
};
|
|
117
|
+
const setLength = (optKey, dataKey = optKey) => {
|
|
118
|
+
const raw = element.dataset[dataKey];
|
|
119
|
+
if (!raw) return;
|
|
120
|
+
options[optKey] = /^\d+(\.\d+)?$/.test(raw.trim()) ? parseFloat(raw) : raw;
|
|
121
|
+
};
|
|
122
|
+
const setJsonArray = (optKey, dataKey = optKey) => {
|
|
123
|
+
const raw = element.dataset[dataKey];
|
|
124
|
+
if (!raw) return;
|
|
125
|
+
const parsed = toArray(raw);
|
|
126
|
+
if (parsed) options[optKey] = parsed;
|
|
127
|
+
else console.warn(`[WaveformPlayer] Invalid ${dataKey} attribute, expected a JSON array:`, raw);
|
|
128
|
+
};
|
|
129
|
+
if (element.dataset.src) options.url = element.dataset.src;
|
|
130
|
+
if (element.dataset.url) options.url = element.dataset.url;
|
|
131
|
+
setNum("height");
|
|
132
|
+
setNum("samples");
|
|
133
|
+
if (element.dataset.preload) {
|
|
134
|
+
options.preload = element.dataset.preload;
|
|
135
|
+
}
|
|
136
|
+
if (element.dataset.crossOrigin) {
|
|
137
|
+
options.crossOrigin = element.dataset.crossOrigin;
|
|
138
|
+
}
|
|
139
|
+
if (element.dataset.audioMode) options.audioMode = element.dataset.audioMode;
|
|
140
|
+
if (element.dataset.style) options.waveformStyle = element.dataset.style;
|
|
141
|
+
if (element.dataset.waveformStyle) options.waveformStyle = element.dataset.waveformStyle;
|
|
142
|
+
if (element.dataset.waveformGradient) options.waveformGradient = element.dataset.waveformGradient;
|
|
143
|
+
setNum("barWidth");
|
|
144
|
+
setNum("barSpacing");
|
|
145
|
+
setNum("barRadius");
|
|
146
|
+
if (element.dataset.buttonAlign) options.buttonAlign = element.dataset.buttonAlign;
|
|
147
|
+
if (element.dataset.layout) options.layout = element.dataset.layout;
|
|
148
|
+
if (element.dataset.buttonStyle) options.buttonStyle = element.dataset.buttonStyle;
|
|
149
|
+
setLength("buttonSize");
|
|
150
|
+
setLength("buttonRadius");
|
|
151
|
+
if (element.dataset.colorPreset) options.colorPreset = element.dataset.colorPreset;
|
|
152
|
+
if (element.dataset.waveformColor) options.waveformColor = parseColorValue(element.dataset.waveformColor);
|
|
153
|
+
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
|
+
setBool("autoplay");
|
|
157
|
+
setBool("showControls");
|
|
158
|
+
setBool("showInfo");
|
|
159
|
+
setBool("showTime");
|
|
160
|
+
setBool("showHoverTime");
|
|
161
|
+
setBool("seekHandle");
|
|
162
|
+
setBool("showBPM", "showBpm");
|
|
163
|
+
setNum("bpm");
|
|
164
|
+
setBool("singlePlay");
|
|
165
|
+
setBool("playOnSeek");
|
|
166
|
+
if (element.dataset.title) options.title = element.dataset.title;
|
|
167
|
+
if (element.dataset.artist) options.artist = element.dataset.artist;
|
|
168
|
+
if (element.dataset.album) options.album = element.dataset.album;
|
|
169
|
+
if (element.dataset.artwork) options.artwork = element.dataset.artwork;
|
|
170
|
+
if (element.dataset.artworkPosition) options.artworkPosition = element.dataset.artworkPosition;
|
|
171
|
+
if (element.dataset.waveform) options.waveform = element.dataset.waveform;
|
|
172
|
+
setJsonArray("markers");
|
|
173
|
+
setNum("playbackRate", "playbackRate", true);
|
|
174
|
+
setBool("showPlaybackSpeed");
|
|
175
|
+
if (element.dataset.playbackRates) {
|
|
176
|
+
const rates = toNumberArray(element.dataset.playbackRates);
|
|
177
|
+
if (rates) options.playbackRates = rates;
|
|
178
|
+
else console.warn("[WaveformPlayer] Invalid playbackRates attribute:", element.dataset.playbackRates);
|
|
179
|
+
}
|
|
180
|
+
setBool("enableMediaSession");
|
|
181
|
+
setBool("showMarkers");
|
|
182
|
+
setBool("accessibleSeek");
|
|
183
|
+
if (element.dataset.seekLabel) options.seekLabel = element.dataset.seekLabel;
|
|
184
|
+
if (element.dataset.seekValueText) options.seekValueText = element.dataset.seekValueText;
|
|
185
|
+
if (element.dataset.errorText) options.errorText = element.dataset.errorText;
|
|
186
|
+
if (element.dataset.playPauseLabel) options.playPauseLabel = element.dataset.playPauseLabel;
|
|
187
|
+
if (element.dataset.speedLabel) options.speedLabel = element.dataset.speedLabel;
|
|
188
|
+
if (element.dataset.artworkAlt) options.artworkAlt = element.dataset.artworkAlt;
|
|
189
|
+
if (element.dataset.unknownTrackText) options.unknownTrackText = element.dataset.unknownTrackText;
|
|
190
|
+
if (element.dataset.playIcon) options.playIcon = element.dataset.playIcon;
|
|
191
|
+
if (element.dataset.pauseIcon) options.pauseIcon = element.dataset.pauseIcon;
|
|
192
|
+
return options;
|
|
193
|
+
}
|
|
194
|
+
function formatSeekValueText(template, ...args) {
|
|
195
|
+
let sequentialIndex = 0;
|
|
196
|
+
return template.replace(/%(?:(\d+)\$)?s/g, (match, position) => {
|
|
197
|
+
const index = position ? Number(position) - 1 : sequentialIndex++;
|
|
198
|
+
return args[index] ?? match;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
function formatTime(seconds) {
|
|
202
|
+
const total = Number(seconds);
|
|
203
|
+
if (!total || !Number.isFinite(total) || total < 0) return "0:00";
|
|
204
|
+
const hrs = Math.floor(total / 3600);
|
|
205
|
+
const mins = Math.floor(total % 3600 / 60);
|
|
206
|
+
const secs = Math.floor(total % 60);
|
|
207
|
+
if (hrs > 0) {
|
|
208
|
+
return `${hrs}:${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
|
|
209
|
+
}
|
|
210
|
+
return `${mins}:${secs.toString().padStart(2, "0")}`;
|
|
211
|
+
}
|
|
212
|
+
var idCounter = 0;
|
|
213
|
+
function generateId(url) {
|
|
214
|
+
const str = url || "audio";
|
|
215
|
+
let hash = 5381;
|
|
216
|
+
for (let i = 0; i < str.length; i++) {
|
|
217
|
+
hash = (hash << 5) + hash + str.charCodeAt(i) | 0;
|
|
218
|
+
}
|
|
219
|
+
return `wp_${(hash >>> 0).toString(36)}_${(idCounter++).toString(36)}`;
|
|
220
|
+
}
|
|
221
|
+
function extractTitleFromUrl(url) {
|
|
222
|
+
if (!url) return "Audio";
|
|
223
|
+
const parts = url.split("/");
|
|
224
|
+
const filename = parts[parts.length - 1];
|
|
225
|
+
const name = filename.split(".")[0];
|
|
226
|
+
return name.replace(/[-_]/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
|
|
227
|
+
}
|
|
228
|
+
function parseColor(color) {
|
|
229
|
+
if (typeof color !== "string") return null;
|
|
230
|
+
const m = color.match(/rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*(?:[,/]\s*([\d.]+)(%?))?/i);
|
|
231
|
+
if (!m) return null;
|
|
232
|
+
const r = Number(m[1]), g = Number(m[2]), b = Number(m[3]);
|
|
233
|
+
if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b)) return null;
|
|
234
|
+
let a = m[4] === void 0 ? 1 : Number(m[4]);
|
|
235
|
+
if (!Number.isFinite(a)) return null;
|
|
236
|
+
if (m[5] === "%") a /= 100;
|
|
237
|
+
return { r, g, b, a: clamp(a, 0, 1) };
|
|
238
|
+
}
|
|
239
|
+
function perceivedBrightness(color) {
|
|
240
|
+
const c = parseColor(color);
|
|
241
|
+
if (!c || c.a <= 0) return null;
|
|
242
|
+
return (c.r * 299 + c.g * 587 + c.b * 114) / 1e3;
|
|
243
|
+
}
|
|
244
|
+
function mergeOptions(...sources) {
|
|
245
|
+
const result = {};
|
|
246
|
+
for (const source of sources) {
|
|
247
|
+
for (const key in source) {
|
|
248
|
+
if (source[key] !== null && source[key] !== void 0) {
|
|
249
|
+
result[key] = source[key];
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
function debounce(func, wait) {
|
|
256
|
+
let timeout;
|
|
257
|
+
return function executedFunction(...args) {
|
|
258
|
+
const later = () => {
|
|
259
|
+
clearTimeout(timeout);
|
|
260
|
+
func(...args);
|
|
261
|
+
};
|
|
262
|
+
clearTimeout(timeout);
|
|
263
|
+
timeout = setTimeout(later, wait);
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
function resampleData(data, targetLength) {
|
|
267
|
+
if (data.length === targetLength) return data;
|
|
268
|
+
if (data.length === 0 || targetLength === 0) return [];
|
|
269
|
+
const result = [];
|
|
270
|
+
if (targetLength > data.length) {
|
|
271
|
+
const ratio = (data.length - 1) / (targetLength - 1);
|
|
272
|
+
for (let i = 0; i < targetLength; i++) {
|
|
273
|
+
const index = i * ratio;
|
|
274
|
+
const lower = Math.floor(index);
|
|
275
|
+
const upper = Math.ceil(index);
|
|
276
|
+
const fraction = index - lower;
|
|
277
|
+
if (upper >= data.length) {
|
|
278
|
+
result.push(data[data.length - 1]);
|
|
279
|
+
} else if (lower === upper) {
|
|
280
|
+
result.push(data[lower]);
|
|
281
|
+
} else {
|
|
282
|
+
const value = data[lower] * (1 - fraction) + data[upper] * fraction;
|
|
283
|
+
result.push(value);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
} else {
|
|
287
|
+
const bucketSize = data.length / targetLength;
|
|
288
|
+
for (let i = 0; i < targetLength; i++) {
|
|
289
|
+
const start = Math.floor(i * bucketSize);
|
|
290
|
+
const end = Math.floor((i + 1) * bucketSize);
|
|
291
|
+
let max = 0;
|
|
292
|
+
let count = 0;
|
|
293
|
+
for (let j = start; j <= end && j < data.length; j++) {
|
|
294
|
+
if (data[j] > max) {
|
|
295
|
+
max = data[j];
|
|
296
|
+
}
|
|
297
|
+
count++;
|
|
298
|
+
}
|
|
299
|
+
if (count === 0) {
|
|
300
|
+
const nearestIndex = Math.min(Math.round(i * bucketSize), data.length - 1);
|
|
301
|
+
max = data[nearestIndex];
|
|
302
|
+
}
|
|
303
|
+
result.push(max);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return result;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// src/js/drawing.js
|
|
310
|
+
function makeFill(ctx, value, canvas, options) {
|
|
311
|
+
if (!Array.isArray(value)) return value;
|
|
312
|
+
if (value.length < 2) return value[0];
|
|
313
|
+
const w = canvas.width;
|
|
314
|
+
const h = canvas.height;
|
|
315
|
+
const dir = options && options.waveformGradient;
|
|
316
|
+
const [x0, y0, x1, y1] = dir === "horizontal" ? [0, 0, w, 0] : dir === "diagonal" ? [0, 0, w, h] : [0, 0, 0, h];
|
|
317
|
+
try {
|
|
318
|
+
const grad = ctx.createLinearGradient(x0, y0, x1, y1);
|
|
319
|
+
value.forEach((c, i) => grad.addColorStop(i / (value.length - 1), c));
|
|
320
|
+
return grad;
|
|
321
|
+
} catch (e) {
|
|
322
|
+
return value[0];
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
function fillBar(ctx, x, y, w, h, radii) {
|
|
326
|
+
const any = Array.isArray(radii) ? radii.some((r) => r > 0) : radii > 0;
|
|
327
|
+
if (any && typeof ctx.roundRect === "function") {
|
|
328
|
+
const max = Math.min(w / 2, Math.abs(h) / 2);
|
|
329
|
+
const clampR = (r) => clamp(r, 0, max);
|
|
330
|
+
ctx.beginPath();
|
|
331
|
+
ctx.roundRect(x, y, w, h, Array.isArray(radii) ? radii.map(clampR) : clampR(radii));
|
|
332
|
+
ctx.fill();
|
|
333
|
+
} else {
|
|
334
|
+
ctx.fillRect(x, y, w, h);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
function barRadiusPx(options, dpr) {
|
|
338
|
+
return (options.barRadius || 0) * dpr;
|
|
339
|
+
}
|
|
340
|
+
function barRadii(options, dpr) {
|
|
341
|
+
const r = barRadiusPx(options, dpr);
|
|
342
|
+
return [r, r, 0, 0];
|
|
343
|
+
}
|
|
344
|
+
function capsulePath(ctx, startX, endX, centerY, barHeight) {
|
|
345
|
+
const r = barHeight / 2;
|
|
346
|
+
ctx.beginPath();
|
|
347
|
+
ctx.moveTo(startX, centerY - r);
|
|
348
|
+
ctx.lineTo(endX - r, centerY - r);
|
|
349
|
+
ctx.arc(endX - r, centerY, r, -Math.PI / 2, Math.PI / 2);
|
|
350
|
+
ctx.lineTo(startX, centerY + r);
|
|
351
|
+
ctx.arc(startX, centerY, r, Math.PI / 2, -Math.PI / 2);
|
|
352
|
+
ctx.closePath();
|
|
353
|
+
}
|
|
354
|
+
function drawBars(ctx, canvas, peaks, progress, options) {
|
|
355
|
+
const dpr = window.devicePixelRatio || 1;
|
|
356
|
+
const barWidth = options.barWidth * dpr;
|
|
357
|
+
const barSpacing = options.barSpacing * dpr;
|
|
358
|
+
const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
|
|
359
|
+
const resampledPeaks = resampleData(peaks, barCount);
|
|
360
|
+
const height = canvas.height;
|
|
361
|
+
const progressWidth = progress * canvas.width;
|
|
362
|
+
const radii = barRadii(options, dpr);
|
|
363
|
+
const baseFill = makeFill(ctx, options.color, canvas, options);
|
|
364
|
+
const progFill = makeFill(ctx, options.progressColor, canvas, options);
|
|
365
|
+
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
366
|
+
ctx.fillStyle = baseFill;
|
|
367
|
+
for (let i = 0; i < resampledPeaks.length; i++) {
|
|
368
|
+
const x = i * (barWidth + barSpacing);
|
|
369
|
+
if (x + barWidth > canvas.width) break;
|
|
370
|
+
const peakHeight = resampledPeaks[i] * height * 0.9;
|
|
371
|
+
const y = height - peakHeight;
|
|
372
|
+
fillBar(ctx, x, y, barWidth, peakHeight, radii);
|
|
373
|
+
}
|
|
374
|
+
ctx.save();
|
|
375
|
+
ctx.beginPath();
|
|
376
|
+
ctx.rect(0, 0, progressWidth, height);
|
|
377
|
+
ctx.clip();
|
|
378
|
+
ctx.fillStyle = progFill;
|
|
379
|
+
for (let i = 0; i < resampledPeaks.length; i++) {
|
|
380
|
+
const x = i * (barWidth + barSpacing);
|
|
381
|
+
if (x > progressWidth) break;
|
|
382
|
+
const peakHeight = resampledPeaks[i] * height * 0.9;
|
|
383
|
+
const y = height - peakHeight;
|
|
384
|
+
fillBar(ctx, x, y, barWidth, peakHeight, radii);
|
|
385
|
+
}
|
|
386
|
+
ctx.restore();
|
|
387
|
+
}
|
|
388
|
+
function drawMirror(ctx, canvas, peaks, progress, options) {
|
|
389
|
+
const dpr = window.devicePixelRatio || 1;
|
|
390
|
+
const barWidth = options.barWidth * dpr;
|
|
391
|
+
const barSpacing = options.barSpacing * dpr;
|
|
392
|
+
const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
|
|
393
|
+
const resampledPeaks = resampleData(peaks, barCount);
|
|
394
|
+
const height = canvas.height;
|
|
395
|
+
const centerY = height / 2;
|
|
396
|
+
const progressWidth = progress * canvas.width;
|
|
397
|
+
const r = barRadiusPx(options, dpr);
|
|
398
|
+
const topRadii = [r, r, 0, 0];
|
|
399
|
+
const botRadii = [0, 0, r, r];
|
|
400
|
+
const baseFill = makeFill(ctx, options.color, canvas, options);
|
|
401
|
+
const progFill = makeFill(ctx, options.progressColor, canvas, options);
|
|
402
|
+
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
403
|
+
ctx.fillStyle = baseFill;
|
|
404
|
+
for (let i = 0; i < resampledPeaks.length; i++) {
|
|
405
|
+
const x = i * (barWidth + barSpacing);
|
|
406
|
+
if (x + barWidth > canvas.width) break;
|
|
407
|
+
const peakHeight = resampledPeaks[i] * height * 0.45;
|
|
408
|
+
fillBar(ctx, x, centerY - peakHeight, barWidth, peakHeight, topRadii);
|
|
409
|
+
fillBar(ctx, x, centerY, barWidth, peakHeight, botRadii);
|
|
410
|
+
}
|
|
411
|
+
ctx.save();
|
|
412
|
+
ctx.beginPath();
|
|
413
|
+
ctx.rect(0, 0, progressWidth, height);
|
|
414
|
+
ctx.clip();
|
|
415
|
+
ctx.fillStyle = progFill;
|
|
416
|
+
for (let i = 0; i < resampledPeaks.length; i++) {
|
|
417
|
+
const x = i * (barWidth + barSpacing);
|
|
418
|
+
if (x > progressWidth) break;
|
|
419
|
+
const peakHeight = resampledPeaks[i] * height * 0.45;
|
|
420
|
+
fillBar(ctx, x, centerY - peakHeight, barWidth, peakHeight, topRadii);
|
|
421
|
+
fillBar(ctx, x, centerY, barWidth, peakHeight, botRadii);
|
|
422
|
+
}
|
|
423
|
+
ctx.restore();
|
|
424
|
+
}
|
|
425
|
+
function drawLine(ctx, canvas, peaks, progress, options) {
|
|
426
|
+
const width = canvas.width;
|
|
427
|
+
const height = canvas.height;
|
|
428
|
+
const centerY = height / 2;
|
|
429
|
+
const amplitude = height * 0.35;
|
|
430
|
+
ctx.clearRect(0, 0, width, height);
|
|
431
|
+
const drawCurve = (color, lineWidth, endProgress = 1, addGlow = false) => {
|
|
432
|
+
const stroke = makeFill(ctx, color, canvas, options);
|
|
433
|
+
const solid = Array.isArray(color) ? color[color.length - 1] : color;
|
|
434
|
+
if (addGlow) {
|
|
435
|
+
ctx.shadowBlur = 12;
|
|
436
|
+
ctx.shadowColor = solid;
|
|
437
|
+
}
|
|
438
|
+
ctx.strokeStyle = stroke;
|
|
439
|
+
ctx.lineWidth = lineWidth;
|
|
440
|
+
ctx.lineCap = "round";
|
|
441
|
+
ctx.lineJoin = "round";
|
|
442
|
+
ctx.beginPath();
|
|
443
|
+
ctx.moveTo(0, centerY);
|
|
444
|
+
const points = [];
|
|
445
|
+
const samples = Math.floor(peaks.length * endProgress);
|
|
446
|
+
for (let i = 0; i < samples; i++) {
|
|
447
|
+
const x = i / (peaks.length - 1) * width;
|
|
448
|
+
const peakValue = peaks[i];
|
|
449
|
+
const waveOffset = Math.sin(i * 0.1) * peakValue;
|
|
450
|
+
const y = centerY + waveOffset * amplitude;
|
|
451
|
+
points.push({ x, y });
|
|
452
|
+
}
|
|
453
|
+
for (let i = 0; i < points.length - 1; i++) {
|
|
454
|
+
const cp1x = points[i].x + (points[i + 1].x - points[i].x) * 0.5;
|
|
455
|
+
const cp1y = points[i].y;
|
|
456
|
+
const cp2x = points[i + 1].x - (points[i + 1].x - points[i].x) * 0.5;
|
|
457
|
+
const cp2y = points[i + 1].y;
|
|
458
|
+
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, points[i + 1].x, points[i + 1].y);
|
|
459
|
+
}
|
|
460
|
+
ctx.stroke();
|
|
461
|
+
if (addGlow) {
|
|
462
|
+
ctx.shadowBlur = 0;
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
ctx.strokeStyle = "rgba(255, 255, 255, 0.03)";
|
|
466
|
+
ctx.lineWidth = 0.5;
|
|
467
|
+
ctx.beginPath();
|
|
468
|
+
ctx.moveTo(0, centerY);
|
|
469
|
+
ctx.lineTo(width, centerY);
|
|
470
|
+
ctx.stroke();
|
|
471
|
+
for (let i = 0; i <= 10; i++) {
|
|
472
|
+
const x = width / 10 * i;
|
|
473
|
+
ctx.beginPath();
|
|
474
|
+
ctx.moveTo(x, 0);
|
|
475
|
+
ctx.lineTo(x, height);
|
|
476
|
+
ctx.stroke();
|
|
477
|
+
}
|
|
478
|
+
drawCurve(options.color, 2, 1, false);
|
|
479
|
+
if (progress > 0) {
|
|
480
|
+
drawCurve(options.progressColor, 3, progress, true);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
function drawBlocks(ctx, canvas, peaks, progress, options) {
|
|
484
|
+
const dpr = window.devicePixelRatio || 1;
|
|
485
|
+
const barWidth = (options.barWidth || 3) * dpr;
|
|
486
|
+
const barSpacing = (options.barSpacing || 1) * dpr;
|
|
487
|
+
const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
|
|
488
|
+
const resampledPeaks = resampleData(peaks, barCount);
|
|
489
|
+
const height = canvas.height;
|
|
490
|
+
const blockSize = 4 * dpr;
|
|
491
|
+
const blockGap = 2 * dpr;
|
|
492
|
+
const progressWidth = progress * canvas.width;
|
|
493
|
+
const centerY = height / 2;
|
|
494
|
+
const baseFill = makeFill(ctx, options.color, canvas, options);
|
|
495
|
+
const progFill = makeFill(ctx, options.progressColor, canvas, options);
|
|
496
|
+
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
497
|
+
for (let i = 0; i < resampledPeaks.length; i++) {
|
|
498
|
+
const x = i * (barWidth + barSpacing);
|
|
499
|
+
if (x + barWidth > canvas.width) break;
|
|
500
|
+
const peakHeight = resampledPeaks[i] * height * 0.9;
|
|
501
|
+
const blockCount = Math.floor(peakHeight / (blockSize + blockGap));
|
|
502
|
+
ctx.fillStyle = x < progressWidth ? progFill : baseFill;
|
|
503
|
+
for (let j = 0; j < blockCount; j++) {
|
|
504
|
+
const blockOffset = j * (blockSize + blockGap);
|
|
505
|
+
ctx.fillRect(x, centerY - blockOffset - blockSize, barWidth, blockSize);
|
|
506
|
+
if (j > 0) {
|
|
507
|
+
ctx.fillRect(x, centerY + blockOffset, barWidth, blockSize);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
function drawDots(ctx, canvas, peaks, progress, options) {
|
|
513
|
+
const dpr = window.devicePixelRatio || 1;
|
|
514
|
+
const barWidth = (options.barWidth || 2) * dpr;
|
|
515
|
+
const barSpacing = (options.barSpacing || 3) * dpr;
|
|
516
|
+
const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
|
|
517
|
+
const resampledPeaks = resampleData(peaks, barCount);
|
|
518
|
+
const height = canvas.height;
|
|
519
|
+
const dotRadius = Math.max(1.5 * dpr, barWidth / 2);
|
|
520
|
+
const progressWidth = progress * canvas.width;
|
|
521
|
+
const centerY = height / 2;
|
|
522
|
+
const baseFill = makeFill(ctx, options.color, canvas, options);
|
|
523
|
+
const progFill = makeFill(ctx, options.progressColor, canvas, options);
|
|
524
|
+
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
525
|
+
for (let i = 0; i < resampledPeaks.length; i++) {
|
|
526
|
+
const x = i * (barWidth + barSpacing) + barWidth / 2;
|
|
527
|
+
if (x > canvas.width) break;
|
|
528
|
+
const peakHeight = resampledPeaks[i] * height * 0.9;
|
|
529
|
+
ctx.fillStyle = x < progressWidth ? progFill : baseFill;
|
|
530
|
+
ctx.beginPath();
|
|
531
|
+
ctx.arc(x, centerY - peakHeight / 2, dotRadius, 0, Math.PI * 2);
|
|
532
|
+
ctx.fill();
|
|
533
|
+
ctx.beginPath();
|
|
534
|
+
ctx.arc(x, centerY + peakHeight / 2, dotRadius, 0, Math.PI * 2);
|
|
535
|
+
ctx.fill();
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
function drawSeekbar(ctx, canvas, peaks, progress, options) {
|
|
539
|
+
const width = canvas.width;
|
|
540
|
+
const height = canvas.height;
|
|
541
|
+
const centerY = height / 2;
|
|
542
|
+
const barHeight = 4;
|
|
543
|
+
const borderRadius = barHeight / 2;
|
|
544
|
+
const active = !!options.seekActive;
|
|
545
|
+
ctx.clearRect(0, 0, width, height);
|
|
546
|
+
ctx.fillStyle = makeFill(ctx, options.color, canvas, options) || "rgba(255, 255, 255, 0.2)";
|
|
547
|
+
capsulePath(ctx, borderRadius, width, centerY, barHeight);
|
|
548
|
+
ctx.fill();
|
|
549
|
+
if (progress > 0) {
|
|
550
|
+
const progressWidth = Math.max(borderRadius * 2, progress * width);
|
|
551
|
+
ctx.save();
|
|
552
|
+
ctx.globalAlpha = options.seekHandle && !active ? 0.7 : 1;
|
|
553
|
+
ctx.fillStyle = makeFill(ctx, options.progressColor, canvas, options) || "rgba(255, 255, 255, 0.9)";
|
|
554
|
+
capsulePath(ctx, borderRadius, progressWidth, centerY, barHeight);
|
|
555
|
+
ctx.fill();
|
|
556
|
+
ctx.restore();
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
var DRAWING_STYLES = {
|
|
560
|
+
"bars": drawBars,
|
|
561
|
+
// Classic vertical bars
|
|
562
|
+
"bar": drawBars,
|
|
563
|
+
"mirror": drawMirror,
|
|
564
|
+
// SoundCloud-style symmetrical
|
|
565
|
+
"line": drawLine,
|
|
566
|
+
// Smooth oscilloscope wave
|
|
567
|
+
"blocks": drawBlocks,
|
|
568
|
+
// LED meter segmented
|
|
569
|
+
"block": drawBlocks,
|
|
570
|
+
"dots": drawDots,
|
|
571
|
+
// Circular points
|
|
572
|
+
"dot": drawDots,
|
|
573
|
+
"seekbar": drawSeekbar
|
|
574
|
+
// Simple progress bar (no waveform)
|
|
575
|
+
};
|
|
576
|
+
function draw(ctx, canvas, peaks, progress, options) {
|
|
577
|
+
const drawFunc = DRAWING_STYLES[options.waveformStyle] || drawBars;
|
|
578
|
+
drawFunc(ctx, canvas, peaks, progress, options);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// src/js/bpm.js
|
|
582
|
+
function detectBPM(buffer) {
|
|
583
|
+
try {
|
|
584
|
+
const channelData = buffer.getChannelData(0);
|
|
585
|
+
const sampleRate = buffer.sampleRate;
|
|
586
|
+
const onsets = detectOnsets(channelData, sampleRate);
|
|
587
|
+
if (onsets.length < 2) return 120;
|
|
588
|
+
const intervals = [];
|
|
589
|
+
for (let i = 1; i < onsets.length; i++) {
|
|
590
|
+
intervals.push((onsets[i] - onsets[i - 1]) / sampleRate);
|
|
591
|
+
}
|
|
592
|
+
const tempoGroups = {};
|
|
593
|
+
intervals.forEach((interval) => {
|
|
594
|
+
const tempo = 60 / interval;
|
|
595
|
+
const bucket = Math.round(tempo / 3) * 3;
|
|
596
|
+
if (bucket > 60 && bucket < 200) {
|
|
597
|
+
tempoGroups[bucket] = (tempoGroups[bucket] || 0) + 1;
|
|
598
|
+
}
|
|
599
|
+
});
|
|
600
|
+
let maxCount = 0;
|
|
601
|
+
let detectedBPM = 120;
|
|
602
|
+
for (const [tempo, count] of Object.entries(tempoGroups)) {
|
|
603
|
+
if (count > maxCount) {
|
|
604
|
+
maxCount = count;
|
|
605
|
+
detectedBPM = parseInt(tempo);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
if (detectedBPM < 70 && tempoGroups[detectedBPM * 2]) {
|
|
609
|
+
detectedBPM *= 2;
|
|
610
|
+
} else if (detectedBPM > 160 && tempoGroups[Math.round(detectedBPM / 2)]) {
|
|
611
|
+
detectedBPM = Math.round(detectedBPM / 2);
|
|
612
|
+
}
|
|
613
|
+
return detectedBPM - 1;
|
|
614
|
+
} catch (e) {
|
|
615
|
+
console.warn("[WaveformPlayer] BPM detection failed:", e);
|
|
616
|
+
return null;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
function detectOnsets(channelData, sampleRate) {
|
|
620
|
+
const windowSize = 2048;
|
|
621
|
+
const hopSize = windowSize / 2;
|
|
622
|
+
const onsets = [];
|
|
623
|
+
let previousEnergy = 0;
|
|
624
|
+
for (let i = 0; i < channelData.length - windowSize; i += hopSize) {
|
|
625
|
+
let energy = 0;
|
|
626
|
+
for (let j = i; j < i + windowSize; j++) {
|
|
627
|
+
energy += channelData[j] * channelData[j];
|
|
628
|
+
}
|
|
629
|
+
energy = energy / windowSize;
|
|
630
|
+
const energyDiff = energy - previousEnergy;
|
|
631
|
+
const threshold = previousEnergy * 1.8 + 0.01;
|
|
632
|
+
if (energyDiff > threshold && energy > 0.01) {
|
|
633
|
+
const lastOnset = onsets[onsets.length - 1] || 0;
|
|
634
|
+
const minDistance = sampleRate * 0.15;
|
|
635
|
+
if (i - lastOnset > minDistance) {
|
|
636
|
+
onsets.push(i);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
previousEnergy = energy * 0.8 + previousEnergy * 0.2;
|
|
640
|
+
}
|
|
641
|
+
return onsets;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// src/js/audio.js
|
|
645
|
+
function extractPeaks(buffer, samples = DEFAULT_SAMPLES) {
|
|
646
|
+
const sampleSize = buffer.length / samples;
|
|
647
|
+
const channels = buffer.numberOfChannels;
|
|
648
|
+
const peaks = [];
|
|
649
|
+
for (let c = 0; c < channels; c++) {
|
|
650
|
+
const chan = buffer.getChannelData(c);
|
|
651
|
+
for (let i = 0; i < samples; i++) {
|
|
652
|
+
const start = ~~(i * sampleSize);
|
|
653
|
+
const end = ~~(start + sampleSize);
|
|
654
|
+
let min = 0;
|
|
655
|
+
let max = 0;
|
|
656
|
+
for (let j = start; j < end; j++) {
|
|
657
|
+
const value = chan[j];
|
|
658
|
+
if (value > max) max = value;
|
|
659
|
+
if (value < min) min = value;
|
|
660
|
+
}
|
|
661
|
+
const peak = Math.max(Math.abs(max), Math.abs(min));
|
|
662
|
+
if (c === 0 || peak > peaks[i]) {
|
|
663
|
+
peaks[i] = peak;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
const maxPeak = maxOf(peaks);
|
|
668
|
+
return maxPeak > 0 ? peaks.map((peak) => peak / maxPeak) : peaks;
|
|
669
|
+
}
|
|
670
|
+
async function generateWaveform(url, samples = DEFAULT_SAMPLES, shouldDetectBPM = false) {
|
|
671
|
+
let audioContext;
|
|
672
|
+
try {
|
|
673
|
+
const AudioCtx = window.AudioContext || /** @type {any} */
|
|
674
|
+
window.webkitAudioContext;
|
|
675
|
+
audioContext = new AudioCtx();
|
|
676
|
+
const response = await fetch(url);
|
|
677
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
678
|
+
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
|
|
679
|
+
let peaks = extractPeaks(audioBuffer, samples);
|
|
680
|
+
peaks = normalizePeaks(peaks);
|
|
681
|
+
let bpm = null;
|
|
682
|
+
if (shouldDetectBPM) {
|
|
683
|
+
bpm = detectBPM(audioBuffer);
|
|
684
|
+
}
|
|
685
|
+
return { peaks, bpm };
|
|
686
|
+
} finally {
|
|
687
|
+
if (audioContext) audioContext.close();
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function generatePlaceholderWaveform(samples = DEFAULT_SAMPLES) {
|
|
691
|
+
const data = [];
|
|
692
|
+
for (let i = 0; i < samples; i++) {
|
|
693
|
+
const base = Math.random() * 0.5 + 0.3;
|
|
694
|
+
const variation = Math.sin(i / samples * Math.PI * 4) * 0.2;
|
|
695
|
+
data.push(clamp(base + variation, 0.1, 1));
|
|
696
|
+
}
|
|
697
|
+
return data;
|
|
698
|
+
}
|
|
699
|
+
function normalizePeaks(peaks, targetMax = 0.95) {
|
|
700
|
+
const maxPeak = maxOf(peaks);
|
|
701
|
+
if (maxPeak === 0 || maxPeak > targetMax) return peaks;
|
|
702
|
+
const scaleFactor = targetMax / maxPeak;
|
|
703
|
+
return peaks.map((peak) => peak * scaleFactor);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// src/js/themes.js
|
|
707
|
+
var LIGHT_THRESHOLD = 128;
|
|
708
|
+
function hasThemeHint(scheme) {
|
|
709
|
+
const root = document.documentElement;
|
|
710
|
+
const body = document.body;
|
|
711
|
+
return root.classList.contains(scheme) || root.classList.contains(`${scheme}-mode`) || root.classList.contains(`theme-${scheme}`) || root.getAttribute("data-theme") === scheme || root.getAttribute("data-color-scheme") === scheme || body.classList.contains(scheme) || body.classList.contains(`${scheme}-mode`) || body.getAttribute("data-theme") === scheme;
|
|
712
|
+
}
|
|
713
|
+
function collectBackdrop(el) {
|
|
714
|
+
let sum = 0;
|
|
715
|
+
let alpha = 0;
|
|
716
|
+
for (let node = el; node && node.nodeType === 1 && alpha < 0.995; node = node.parentElement) {
|
|
717
|
+
const c = parseColor(getComputedStyle(node).backgroundColor);
|
|
718
|
+
if (!c || c.a <= 0) continue;
|
|
719
|
+
const weight = c.a * (1 - alpha);
|
|
720
|
+
sum += (c.r * 299 + c.g * 587 + c.b * 114) / 1e3 * weight;
|
|
721
|
+
alpha += weight;
|
|
722
|
+
}
|
|
723
|
+
return { sum, alpha };
|
|
724
|
+
}
|
|
725
|
+
function detectCanvasScheme() {
|
|
726
|
+
const text = perceivedBrightness(getComputedStyle(document.body).color);
|
|
727
|
+
if (text !== null) return text > LIGHT_THRESHOLD ? "dark" : "light";
|
|
728
|
+
if (window.matchMedia) {
|
|
729
|
+
if (window.matchMedia("(prefers-color-scheme: dark)").matches) return "dark";
|
|
730
|
+
if (window.matchMedia("(prefers-color-scheme: light)").matches) return "light";
|
|
731
|
+
}
|
|
732
|
+
return "dark";
|
|
733
|
+
}
|
|
734
|
+
function detectColorScheme(el) {
|
|
735
|
+
if (hasThemeHint("dark")) return "dark";
|
|
736
|
+
if (hasThemeHint("light")) return "light";
|
|
737
|
+
try {
|
|
738
|
+
const start = el && el.nodeType === 1 ? el : document.body;
|
|
739
|
+
const { sum, alpha } = collectBackdrop(start);
|
|
740
|
+
const canvas = detectCanvasScheme();
|
|
741
|
+
const brightness = sum + (canvas === "dark" ? 0 : 255) * (1 - alpha);
|
|
742
|
+
if (brightness > LIGHT_THRESHOLD) return "light";
|
|
743
|
+
if (brightness < LIGHT_THRESHOLD) return "dark";
|
|
744
|
+
return canvas;
|
|
745
|
+
} catch (e) {
|
|
746
|
+
return "dark";
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
var COLOR_PRESETS = {
|
|
750
|
+
dark: {
|
|
751
|
+
waveformColor: "rgba(255, 255, 255, 0.3)",
|
|
752
|
+
progressColor: "rgba(255, 255, 255, 0.9)"
|
|
753
|
+
},
|
|
754
|
+
light: {
|
|
755
|
+
waveformColor: "rgba(0, 0, 0, 0.2)",
|
|
756
|
+
progressColor: "rgba(0, 0, 0, 0.8)"
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
function getColorPreset(presetName, el) {
|
|
760
|
+
if (presetName && COLOR_PRESETS[presetName]) {
|
|
761
|
+
return COLOR_PRESETS[presetName];
|
|
762
|
+
}
|
|
763
|
+
const detected = detectColorScheme(el);
|
|
764
|
+
return COLOR_PRESETS[detected];
|
|
765
|
+
}
|
|
766
|
+
var DEFAULT_OPTIONS = {
|
|
767
|
+
// Core settings
|
|
768
|
+
url: "",
|
|
769
|
+
height: 64,
|
|
770
|
+
// Source peak resolution for LIVE decode (ignored when peaks are supplied).
|
|
771
|
+
// The drawer resamples these to fit canvasWidth / (barWidth + barSpacing)
|
|
772
|
+
// bars, so this is fidelity headroom, not the visible bar count. 1800 (the
|
|
773
|
+
// SoundCloud/WaveformGen figure) keeps wide / high-DPI waveforms crisp; the
|
|
774
|
+
// every-frame scan means a higher value costs no extra extraction time.
|
|
775
|
+
samples: DEFAULT_SAMPLES,
|
|
776
|
+
preload: "metadata",
|
|
777
|
+
// CORS mode for the underlying <audio> element. Left null by default so the
|
|
778
|
+
// player behaves like a plain <audio> and never forces a CORS request —
|
|
779
|
+
// setting 'anonymous' here would break playback of media hosted on origins
|
|
780
|
+
// that don't send Access-Control-Allow-Origin (default-config S3/CDN). The
|
|
781
|
+
// playback element is never fed to createMediaElementSource, so it never
|
|
782
|
+
// needs CORS-clean media; peak analysis uses a separate fetch() path with
|
|
783
|
+
// its own placeholder fallback. Set 'anonymous' / 'use-credentials' only if
|
|
784
|
+
// you specifically need it. See issue #18.
|
|
785
|
+
crossOrigin: null,
|
|
786
|
+
// Audio mode — 'self' = player owns the <audio> element (default, current
|
|
787
|
+
// behavior). 'external' = player is a visualization-only surface; no audio
|
|
788
|
+
// element is created, play() dispatches `waveformplayer:request-play`
|
|
789
|
+
// instead of calling audio.play(), and setPlayingState/setProgress are
|
|
790
|
+
// expected to be driven by an external controller (e.g. WaveformBar).
|
|
791
|
+
audioMode: "self",
|
|
792
|
+
// Playback
|
|
793
|
+
playbackRate: 1,
|
|
794
|
+
showPlaybackSpeed: false,
|
|
795
|
+
playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2],
|
|
796
|
+
// Layout Options
|
|
797
|
+
buttonAlign: "auto",
|
|
798
|
+
// Player layout. 'default' = play button + waveform with a left-aligned
|
|
799
|
+
// info row below. 'preview' = compact: the title is centered under the
|
|
800
|
+
// waveform and the meta row (time / speed / BPM) is trimmed — ideal for
|
|
801
|
+
// sample-pack sample previews and dense grids.
|
|
802
|
+
layout: "default",
|
|
803
|
+
// Play/pause button style. 'circle' = bordered circle (default).
|
|
804
|
+
// 'minimal' = a bare play/pause glyph with no circle — the look sample-pack
|
|
805
|
+
// and beat stores use in their preview grids.
|
|
806
|
+
buttonStyle: "circle",
|
|
807
|
+
// Play/pause button size. null = the stylesheet default (36px circle /
|
|
808
|
+
// proportional minimal). A number is treated as px; a string (e.g. '4rem')
|
|
809
|
+
// is used verbatim. Sets the `--wfp-btn-size` CSS var, which scales BOTH
|
|
810
|
+
// styles — box and glyph — proportionally.
|
|
811
|
+
buttonSize: null,
|
|
812
|
+
// Play/pause button corner radius. null = the stylesheet default (50%, a
|
|
813
|
+
// circle). A number is treated as px; a string (e.g. '8px') is used
|
|
814
|
+
// verbatim. Set 0 for a square button. Sets the `--wfp-btn-radius` CSS var,
|
|
815
|
+
// which shapes the 'circle' style's box — the bare 'minimal' glyph has no
|
|
816
|
+
// box to round, so this is a no-op there.
|
|
817
|
+
buttonRadius: null,
|
|
818
|
+
// Default waveform style
|
|
819
|
+
waveformStyle: "mirror",
|
|
820
|
+
barWidth: 2,
|
|
821
|
+
barSpacing: 0,
|
|
822
|
+
// Rounded bar caps (px). 0 = square; 1 = soft caps (default). Applies to bars/mirror.
|
|
823
|
+
barRadius: 1,
|
|
824
|
+
// Gradient axis when waveformColor/progressColor is an array of stops:
|
|
825
|
+
// 'vertical' (top->bottom canvas gradient), 'horizontal' (hue sweep across the
|
|
826
|
+
// waveform) or 'diagonal'. Ignored for single colours.
|
|
827
|
+
waveformGradient: "vertical",
|
|
828
|
+
// Color preset: null = auto-detect, 'dark' = force dark, 'light' = force light
|
|
829
|
+
colorPreset: null,
|
|
830
|
+
// Canvas colours (null = inherit the resolved preset; arrays = gradient
|
|
831
|
+
// stops, see waveformGradient). The DOM chrome (button, title, meta) is
|
|
832
|
+
// themed via CSS variables (--wfp-button-color / --wfp-text-color /
|
|
833
|
+
// --wfp-text-secondary-color), not JS options.
|
|
834
|
+
waveformColor: null,
|
|
835
|
+
progressColor: null,
|
|
836
|
+
// Features
|
|
837
|
+
autoplay: false,
|
|
838
|
+
showControls: true,
|
|
839
|
+
showInfo: true,
|
|
840
|
+
showTime: true,
|
|
841
|
+
showHoverTime: false,
|
|
842
|
+
// Show a draggable circle handle + hover brightness-lift on the SEEKBAR
|
|
843
|
+
// style only (it's meaningless on a waveform, where the fill-edge is the
|
|
844
|
+
// playhead). Off by default; the bar turns it on. Drag-to-scrub works
|
|
845
|
+
// regardless of this.
|
|
846
|
+
seekHandle: false,
|
|
847
|
+
showBPM: false,
|
|
848
|
+
// Known BPM to display in the badge (with showBPM). Wins over auto-detection
|
|
849
|
+
// — set it when peaks are pre-generated so the tempo still shows. null = auto.
|
|
850
|
+
bpm: null,
|
|
851
|
+
singlePlay: true,
|
|
852
|
+
playOnSeek: true,
|
|
853
|
+
enableMediaSession: true,
|
|
854
|
+
// Markers
|
|
855
|
+
markers: [],
|
|
856
|
+
showMarkers: true,
|
|
857
|
+
// Accessibility — expose the waveform as a keyboard-operable slider
|
|
858
|
+
// (role="slider" + ARIA value attributes + arrow/page/home/end seeking).
|
|
859
|
+
// seekLabel sets the slider's accessible name; when null it falls back
|
|
860
|
+
// to the track title, then 'Seek'.
|
|
861
|
+
// seekValueText templates the slider's spoken aria-valuetext: %1$s is the
|
|
862
|
+
// current time and %2$s the total duration (both formatted M:SS). When null
|
|
863
|
+
// it falls back to '%1$s of %2$s'. Lets consumers localize the connective
|
|
864
|
+
// text without reformatting the times.
|
|
865
|
+
accessibleSeek: true,
|
|
866
|
+
seekLabel: null,
|
|
867
|
+
seekValueText: null,
|
|
868
|
+
// Content
|
|
869
|
+
title: null,
|
|
870
|
+
artist: null,
|
|
871
|
+
artwork: null,
|
|
872
|
+
// Where the `artwork` image renders. 'info' = the info row beside the title
|
|
873
|
+
// (needs showInfo). 'button' = the cover becomes the play/pause button,
|
|
874
|
+
// which still works with the info row hidden. Only ONE placement ever
|
|
875
|
+
// renders, so the same cover can't appear twice.
|
|
876
|
+
//
|
|
877
|
+
// 'button' is self-contained: the stylesheet drops the button's ring and
|
|
878
|
+
// swaps its defaults for cover-sized ones (64px, 8px rounding), because the
|
|
879
|
+
// transport defaults are wrong for artwork in both directions — 36px
|
|
880
|
+
// smudges a cover, and 50% crops square art into a circle. buttonSize /
|
|
881
|
+
// buttonRadius still override it if you want a different tile.
|
|
882
|
+
artworkPosition: "info",
|
|
883
|
+
album: "",
|
|
884
|
+
// Message shown in the error state when audio fails to load.
|
|
885
|
+
errorText: "Unable to load audio",
|
|
886
|
+
// Localizable UI strings (alongside seekLabel / seekValueText / errorText).
|
|
887
|
+
// These are screen-reader / assistive-tech facing, so translate them for
|
|
888
|
+
// non-English UIs. playPauseLabel/speedLabel are aria-labels; artworkAlt is
|
|
889
|
+
// the cover image alt text; unknownTrackText is the Media Session (lock-
|
|
890
|
+
// screen) title fallback used when no track title is set.
|
|
891
|
+
playPauseLabel: "Play/Pause",
|
|
892
|
+
speedLabel: "Playback speed",
|
|
893
|
+
artworkAlt: "Album artwork",
|
|
894
|
+
unknownTrackText: "Unknown Track",
|
|
895
|
+
// Icons (SVG)
|
|
896
|
+
playIcon: '<svg viewBox="0 0 24 24" width="16" height="16"><path d="M8 5v14l11-7z"/></svg>',
|
|
897
|
+
pauseIcon: '<svg viewBox="0 0 24 24" width="16" height="16"><path d="M6 4h4v16H6zM14 4h4v16h-4z"/></svg>',
|
|
898
|
+
// Callbacks
|
|
899
|
+
onLoad: null,
|
|
900
|
+
onPlay: null,
|
|
901
|
+
onPause: null,
|
|
902
|
+
onEnd: null,
|
|
903
|
+
onError: null,
|
|
904
|
+
onTimeUpdate: null,
|
|
905
|
+
// Optional queue navigation — when set, the player registers Media Session
|
|
906
|
+
// nexttrack/previoustrack handlers (lock-screen skip buttons). Called with
|
|
907
|
+
// the player instance; wired by waveform-bar / -playlist.
|
|
908
|
+
onNextTrack: null,
|
|
909
|
+
onPreviousTrack: null
|
|
910
|
+
};
|
|
911
|
+
var STYLE_DEFAULTS = {
|
|
912
|
+
bars: { barWidth: 3, barSpacing: 1 },
|
|
913
|
+
mirror: { barWidth: 2, barSpacing: 2 },
|
|
914
|
+
line: { barWidth: 2, barSpacing: 0 },
|
|
915
|
+
blocks: { barWidth: 4, barSpacing: 2 },
|
|
916
|
+
dots: { barWidth: 3, barSpacing: 3 },
|
|
917
|
+
seekbar: { barWidth: 1, barSpacing: 0 }
|
|
918
|
+
};
|
|
919
|
+
var BUTTON_ALIGNMENTS = ["auto", "top", "center", "bottom"];
|
|
920
|
+
var PLAYBACK_RATE_MIN = 0.25;
|
|
921
|
+
var PLAYBACK_RATE_MAX = 4;
|
|
922
|
+
var ENUMS = {
|
|
923
|
+
buttonAlign: BUTTON_ALIGNMENTS,
|
|
924
|
+
layout: ["default", "preview"],
|
|
925
|
+
buttonStyle: ["circle", "minimal"],
|
|
926
|
+
artworkPosition: ["info", "button"],
|
|
927
|
+
waveformStyle: Object.keys(STYLE_DEFAULTS),
|
|
928
|
+
waveformGradient: ["vertical", "horizontal", "diagonal"],
|
|
929
|
+
audioMode: ["self", "external"],
|
|
930
|
+
preload: ["none", "metadata", "auto"],
|
|
931
|
+
colorPreset: Object.keys(COLOR_PRESETS),
|
|
932
|
+
// Anything other than these two makes the browser fall back to 'anonymous',
|
|
933
|
+
// which forces a CORS request the caller never asked for — so a bad value
|
|
934
|
+
// has to resolve to null (no crossorigin attribute), not pass through.
|
|
935
|
+
crossOrigin: ["anonymous", "use-credentials"]
|
|
936
|
+
};
|
|
937
|
+
var NUMBERS = {
|
|
938
|
+
height: { min: 1, integer: true },
|
|
939
|
+
samples: { min: 1, integer: true },
|
|
940
|
+
barWidth: { min: 0 },
|
|
941
|
+
barSpacing: { min: 0 },
|
|
942
|
+
barRadius: { min: 0 },
|
|
943
|
+
bpm: { min: 1 },
|
|
944
|
+
// Matches the clamp in setPlaybackRate() — the menu must not offer a rate
|
|
945
|
+
// the setter would then silently refuse.
|
|
946
|
+
playbackRate: { min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX }
|
|
947
|
+
};
|
|
948
|
+
var BOOLEANS = [
|
|
949
|
+
"autoplay",
|
|
950
|
+
"showControls",
|
|
951
|
+
"showInfo",
|
|
952
|
+
"showTime",
|
|
953
|
+
"showHoverTime",
|
|
954
|
+
"seekHandle",
|
|
955
|
+
"showBPM",
|
|
956
|
+
"singlePlay",
|
|
957
|
+
"playOnSeek",
|
|
958
|
+
"enableMediaSession",
|
|
959
|
+
"showMarkers",
|
|
960
|
+
"accessibleSeek",
|
|
961
|
+
"showPlaybackSpeed"
|
|
962
|
+
];
|
|
963
|
+
var CALLBACKS = [
|
|
964
|
+
"onLoad",
|
|
965
|
+
"onPlay",
|
|
966
|
+
"onPause",
|
|
967
|
+
"onEnd",
|
|
968
|
+
"onError",
|
|
969
|
+
"onTimeUpdate",
|
|
970
|
+
"onNextTrack",
|
|
971
|
+
"onPreviousTrack"
|
|
972
|
+
];
|
|
973
|
+
function warnInvalid(key, value) {
|
|
974
|
+
console.warn(`[WaveformPlayer] Invalid ${key} option, using default:`, value);
|
|
975
|
+
}
|
|
976
|
+
function normalizeMarkers(value) {
|
|
977
|
+
const list = toArray(value);
|
|
978
|
+
if (!list) {
|
|
979
|
+
if (value != null) warnInvalid("markers", value);
|
|
980
|
+
return [];
|
|
981
|
+
}
|
|
982
|
+
return list.reduce((markers, marker) => {
|
|
983
|
+
const time = marker && typeof marker === "object" ? toFiniteNumber(marker.time, null, { min: 0 }) : null;
|
|
984
|
+
if (time === null) {
|
|
985
|
+
warnInvalid("marker", marker);
|
|
986
|
+
return markers;
|
|
987
|
+
}
|
|
988
|
+
markers.push({ ...marker, time, label: marker.label == null ? "" : marker.label });
|
|
989
|
+
return markers;
|
|
990
|
+
}, []);
|
|
991
|
+
}
|
|
992
|
+
function normalizeOptions(options) {
|
|
993
|
+
const supplied = (key) => options[key] != null;
|
|
994
|
+
const reject = (key) => {
|
|
995
|
+
warnInvalid(key, options[key]);
|
|
996
|
+
options[key] = DEFAULT_OPTIONS[key];
|
|
997
|
+
};
|
|
998
|
+
for (const [key, range] of Object.entries(NUMBERS)) {
|
|
999
|
+
if (!supplied(key)) continue;
|
|
1000
|
+
const n = toFiniteNumber(options[key], null, range);
|
|
1001
|
+
if (n === null) reject(key);
|
|
1002
|
+
else options[key] = n;
|
|
1003
|
+
}
|
|
1004
|
+
for (const [key, allowed] of Object.entries(ENUMS)) {
|
|
1005
|
+
if (supplied(key) && toEnum(options[key], allowed) === null) reject(key);
|
|
1006
|
+
}
|
|
1007
|
+
for (const key of BOOLEANS) {
|
|
1008
|
+
options[key] = toBool(options[key]);
|
|
1009
|
+
}
|
|
1010
|
+
for (const key of CALLBACKS) {
|
|
1011
|
+
if (supplied(key) && typeof options[key] !== "function") reject(key);
|
|
1012
|
+
}
|
|
1013
|
+
if (supplied("playbackRates")) {
|
|
1014
|
+
const rates = toNumberArray(options.playbackRates, {
|
|
1015
|
+
min: PLAYBACK_RATE_MIN,
|
|
1016
|
+
max: PLAYBACK_RATE_MAX,
|
|
1017
|
+
fallback: null
|
|
1018
|
+
});
|
|
1019
|
+
if (rates === null) reject("playbackRates");
|
|
1020
|
+
else options.playbackRates = rates;
|
|
1021
|
+
}
|
|
1022
|
+
options.markers = normalizeMarkers(options.markers);
|
|
1023
|
+
for (const key of ["buttonSize", "buttonRadius"]) {
|
|
1024
|
+
if (!supplied(key)) continue;
|
|
1025
|
+
const value = options[key];
|
|
1026
|
+
const ok = typeof value === "number" ? Number.isFinite(value) : typeof value === "string" && value.trim() !== "";
|
|
1027
|
+
if (!ok) reject(key);
|
|
1028
|
+
}
|
|
1029
|
+
for (const key of ["waveformColor", "progressColor"]) {
|
|
1030
|
+
if (!supplied(key)) continue;
|
|
1031
|
+
const value = options[key];
|
|
1032
|
+
if (!(typeof value === "string" && value.trim() !== "") && !Array.isArray(value)) reject(key);
|
|
1033
|
+
}
|
|
1034
|
+
return options;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
// src/js/core.js
|
|
1038
|
+
var ARTWORK_FALLBACK = "data:image/svg+xml," + encodeURIComponent(
|
|
1039
|
+
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="#71717a" fill-opacity="0.15"/><g fill="none" stroke="#a1a1aa" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="17" r="2.2"/><circle cx="17" cy="15" r="2.2"/><path d="M10.2 17V7l9-1.6v9"/></g></svg>'
|
|
1040
|
+
);
|
|
1041
|
+
var SEEK_STEP_SECONDS = 5;
|
|
1042
|
+
var SEEK_PAGE_SECONDS = 10;
|
|
1043
|
+
var INTERACTIVE_ELEMENTS = 'button, a[href], input, [role="slider"]';
|
|
1044
|
+
var WaveformPlayer = class _WaveformPlayer {
|
|
1045
|
+
/** @type {Map<string, WaveformPlayer>} */
|
|
1046
|
+
static instances = /* @__PURE__ */ new Map();
|
|
1047
|
+
/** @type {WaveformPlayer|null} */
|
|
1048
|
+
static currentlyPlaying = null;
|
|
1049
|
+
/**
|
|
1050
|
+
* Create a new WaveformPlayer instance.
|
|
1051
|
+
*
|
|
1052
|
+
* Resolves the container, merges options (defaults < `data-*` attributes <
|
|
1053
|
+
* constructor options), applies the colour preset and style-specific
|
|
1054
|
+
* defaults, registers the instance in the static map, and kicks off
|
|
1055
|
+
* {@link WaveformPlayer#init}. A `waveformplayer:ready` event is dispatched
|
|
1056
|
+
* ~100ms later, once initialization has settled.
|
|
1057
|
+
*
|
|
1058
|
+
* @param {string|HTMLElement} container - Container element, or a CSS
|
|
1059
|
+
* selector resolved with `document.querySelector`.
|
|
1060
|
+
* @param {Object} [options={}] - Player options. Accepts the shorthand
|
|
1061
|
+
* aliases `style` (→ `waveformStyle`) and `src` (→ `url`); the canonical
|
|
1062
|
+
* names win if both are supplied.
|
|
1063
|
+
* @throws {Error} If the container element cannot be found.
|
|
1064
|
+
* @fires WaveformPlayer#waveformplayer:ready
|
|
1065
|
+
*/
|
|
1066
|
+
constructor(container, options = {}) {
|
|
1067
|
+
this.container = typeof container === "string" ? document.querySelector(container) : container;
|
|
1068
|
+
if (!this.container) {
|
|
1069
|
+
throw new Error("[WaveformPlayer] Container element not found");
|
|
1070
|
+
}
|
|
1071
|
+
const dataOptions = parseDataAttributes(this.container);
|
|
1072
|
+
const userOptions = { ...options };
|
|
1073
|
+
if (userOptions.style && !userOptions.waveformStyle) userOptions.waveformStyle = userOptions.style;
|
|
1074
|
+
if (userOptions.src && !userOptions.url) userOptions.url = userOptions.src;
|
|
1075
|
+
this.options = normalizeOptions(mergeOptions(DEFAULT_OPTIONS, dataOptions, userOptions));
|
|
1076
|
+
const preset = getColorPreset(this.options.colorPreset, this.container);
|
|
1077
|
+
this._autoTheme = this.options.colorPreset == null || !COLOR_PRESETS[this.options.colorPreset];
|
|
1078
|
+
this._presetKeys = [];
|
|
1079
|
+
this._scheme = this.options.colorPreset && COLOR_PRESETS[this.options.colorPreset] ? this.options.colorPreset : detectColorScheme(this.container);
|
|
1080
|
+
for (const [key, value] of Object.entries(preset)) {
|
|
1081
|
+
if (this.options[key] === null || this.options[key] === void 0) {
|
|
1082
|
+
this.options[key] = value;
|
|
1083
|
+
this._presetKeys.push(key);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
const styleDefaults = STYLE_DEFAULTS[this.options.waveformStyle];
|
|
1087
|
+
if (styleDefaults) {
|
|
1088
|
+
if (dataOptions.barWidth === void 0 && options.barWidth === void 0) {
|
|
1089
|
+
this.options.barWidth = styleDefaults.barWidth;
|
|
1090
|
+
}
|
|
1091
|
+
if (dataOptions.barSpacing === void 0 && options.barSpacing === void 0) {
|
|
1092
|
+
this.options.barSpacing = styleDefaults.barSpacing;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
this.audio = null;
|
|
1096
|
+
this.canvas = null;
|
|
1097
|
+
this.ctx = null;
|
|
1098
|
+
this.waveformData = [];
|
|
1099
|
+
this.progress = 0;
|
|
1100
|
+
this._activeMarkerIndex = -1;
|
|
1101
|
+
this._markerLabelTimer = null;
|
|
1102
|
+
this.isPlaying = false;
|
|
1103
|
+
this.isLoading = false;
|
|
1104
|
+
this.hasError = false;
|
|
1105
|
+
this.updateTimer = null;
|
|
1106
|
+
this.resizeObserver = null;
|
|
1107
|
+
this._ac = new AbortController();
|
|
1108
|
+
this.id = this.container.id || generateId(this.options.url);
|
|
1109
|
+
_WaveformPlayer.instances.set(this.id, this);
|
|
1110
|
+
_WaveformPlayer._watchTheme();
|
|
1111
|
+
try {
|
|
1112
|
+
this.init();
|
|
1113
|
+
} catch (error) {
|
|
1114
|
+
_WaveformPlayer.instances.delete(this.id);
|
|
1115
|
+
this._ac.abort();
|
|
1116
|
+
throw error;
|
|
1117
|
+
}
|
|
1118
|
+
setTimeout(() => {
|
|
1119
|
+
this._emit("waveformplayer:ready", { player: this, url: this.options.url });
|
|
1120
|
+
}, 100);
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* Build and dispatch a bubbling `waveformplayer:*` CustomEvent on the
|
|
1124
|
+
* container, returning the event so cancelable (request-*) events can have
|
|
1125
|
+
* their `defaultPrevented` checked. Single source of truth for the event
|
|
1126
|
+
* shape — every player event bubbles and carries the supplied detail.
|
|
1127
|
+
* @param {string} type - Full event type, e.g. `'waveformplayer:play'`.
|
|
1128
|
+
* @param {Object} detail - Event detail payload.
|
|
1129
|
+
* @param {boolean} [cancelable=false] - Whether the event is cancelable.
|
|
1130
|
+
* @returns {CustomEvent} The dispatched event.
|
|
1131
|
+
* @private
|
|
1132
|
+
*/
|
|
1133
|
+
_emit(type, detail, cancelable = false) {
|
|
1134
|
+
const event = new CustomEvent(type, { bubbles: true, cancelable, detail });
|
|
1135
|
+
this.container.dispatchEvent(event);
|
|
1136
|
+
return event;
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* External-mode seek request: dispatch a cancelable
|
|
1140
|
+
* `waveformplayer:request-seek` and, unless the controller calls
|
|
1141
|
+
* `preventDefault()`, optimistically advance the local progress overlay so
|
|
1142
|
+
* the canvas repaints at once. Shared by the keyboard slider and canvas click.
|
|
1143
|
+
* @param {number} percent - Target position as a 0..1 fraction.
|
|
1144
|
+
* @private
|
|
1145
|
+
* @fires WaveformPlayer#waveformplayer:request-seek
|
|
1146
|
+
*/
|
|
1147
|
+
_requestSeek(percent) {
|
|
1148
|
+
const evt = this._emit("waveformplayer:request-seek", { ...this._buildTrackDetail(), percent }, true);
|
|
1149
|
+
if (!evt.defaultPrevented) {
|
|
1150
|
+
this.progress = percent;
|
|
1151
|
+
this.drawWaveform?.();
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
// ============================================
|
|
1155
|
+
// Initialization
|
|
1156
|
+
// ============================================
|
|
1157
|
+
/**
|
|
1158
|
+
* Initialize the player: build the DOM, create the audio element (self
|
|
1159
|
+
* mode only), wire up the feature controls (speed, keyboard, accessible
|
|
1160
|
+
* seek), bind events, attach the resize observer, then size the canvas and
|
|
1161
|
+
* — if a `url` option was given — load it and optionally autoplay.
|
|
1162
|
+
* @private
|
|
1163
|
+
*/
|
|
1164
|
+
init() {
|
|
1165
|
+
this.createDOM();
|
|
1166
|
+
this.createAudio();
|
|
1167
|
+
this.initPlaybackSpeed();
|
|
1168
|
+
this.initKeyboardControls();
|
|
1169
|
+
this.initSeekControl();
|
|
1170
|
+
this.bindEvents();
|
|
1171
|
+
this.setupResizeObserver();
|
|
1172
|
+
requestAnimationFrame(() => {
|
|
1173
|
+
this.resizeCanvas();
|
|
1174
|
+
if (this.options.url) {
|
|
1175
|
+
this.load(this.options.url).then(() => {
|
|
1176
|
+
if (this.options.autoplay) {
|
|
1177
|
+
this.play()?.catch(() => {
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
}).catch((error) => {
|
|
1181
|
+
console.error("[WaveformPlayer] Failed to load audio:", error);
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
/**
|
|
1187
|
+
* Build the player's DOM tree inside the container and cache element
|
|
1188
|
+
* references.
|
|
1189
|
+
*
|
|
1190
|
+
* Clears the container, resolves button alignment (`auto` → `bottom` for
|
|
1191
|
+
* the `bars` style, `center` otherwise), and conditionally renders the play
|
|
1192
|
+
* button, info row (artwork/title/artist), BPM badge, playback-speed
|
|
1193
|
+
* menu, and time display based on the relevant `show*` options. Caches the
|
|
1194
|
+
* canvas, controls, and text elements onto `this`, then sizes the canvas.
|
|
1195
|
+
* @private
|
|
1196
|
+
*/
|
|
1197
|
+
createDOM() {
|
|
1198
|
+
this.container.innerHTML = "";
|
|
1199
|
+
this.container.className = "waveform-player";
|
|
1200
|
+
let buttonAlign = BUTTON_ALIGNMENTS.includes(this.options.buttonAlign) ? this.options.buttonAlign : "auto";
|
|
1201
|
+
if (buttonAlign === "auto") {
|
|
1202
|
+
const style = this.options.waveformStyle;
|
|
1203
|
+
if (style === "bars") {
|
|
1204
|
+
buttonAlign = "bottom";
|
|
1205
|
+
} else {
|
|
1206
|
+
buttonAlign = "center";
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
const isPreview = this.options.layout === "preview";
|
|
1210
|
+
if (isPreview) {
|
|
1211
|
+
this.container.classList.add("waveform-layout-preview");
|
|
1212
|
+
}
|
|
1213
|
+
this.container.classList.toggle("waveform-theme-light", this._scheme === "light");
|
|
1214
|
+
const buttonVars = [];
|
|
1215
|
+
if (this.options.buttonSize != null) {
|
|
1216
|
+
buttonVars.push(`--wfp-btn-size: ${formatCssLength(this.options.buttonSize)}`);
|
|
1217
|
+
}
|
|
1218
|
+
if (this.options.buttonRadius != null) {
|
|
1219
|
+
buttonVars.push(`--wfp-btn-radius: ${formatCssLength(this.options.buttonRadius)}`);
|
|
1220
|
+
}
|
|
1221
|
+
const buttonStyleAttr = buttonVars.length ? ` style="${buttonVars.join("; ")};"` : "";
|
|
1222
|
+
const artworkOnButton = this.options.artworkPosition === "button" && this.options.artwork;
|
|
1223
|
+
const buttonArtworkHTML = artworkOnButton ? `<img class="waveform-btn-artwork" src="${escapeHtml(this.options.artwork)}" alt="" aria-hidden="true">` : "";
|
|
1224
|
+
const buttonHTML = this.options.showControls ? `
|
|
1225
|
+
<button class="waveform-btn${this.options.buttonStyle === "minimal" ? " waveform-btn-minimal" : ""}${artworkOnButton ? " waveform-btn-has-artwork" : ""}" aria-label="${escapeHtml(this.options.playPauseLabel)}"${buttonStyleAttr}>
|
|
1226
|
+
${buttonArtworkHTML}
|
|
1227
|
+
<span class="waveform-icon-play">${this.options.playIcon}</span>
|
|
1228
|
+
<span class="waveform-icon-pause" style="display:none;">${this.options.pauseIcon}</span>
|
|
1229
|
+
</button>
|
|
1230
|
+
` : "";
|
|
1231
|
+
const infoHTML = this.options.showInfo ? `
|
|
1232
|
+
<div class="waveform-info">
|
|
1233
|
+
${this.options.artworkPosition !== "button" && this.options.artwork ? `
|
|
1234
|
+
<img class="waveform-artwork" src="${escapeHtml(this.options.artwork)}" alt="${escapeHtml(this.options.artworkAlt)}" style="
|
|
1235
|
+
width: 40px;
|
|
1236
|
+
height: 40px;
|
|
1237
|
+
border-radius: 4px;
|
|
1238
|
+
object-fit: cover;
|
|
1239
|
+
flex-shrink: 0;
|
|
1240
|
+
">
|
|
1241
|
+
` : ""}
|
|
1242
|
+
<div class="waveform-text">
|
|
1243
|
+
<span class="waveform-title"></span>
|
|
1244
|
+
${this.options.artist ? `<span class="waveform-artist">${escapeHtml(this.options.artist)}</span>` : ""}
|
|
1245
|
+
</div>
|
|
1246
|
+
<div class="waveform-meta" style="display: flex; align-items: center; gap: 1rem;">
|
|
1247
|
+
${this.options.showBPM ? `
|
|
1248
|
+
<span class="waveform-bpm" style="display: none;">
|
|
1249
|
+
<span class="bpm-value">--</span> BPM
|
|
1250
|
+
</span>
|
|
1251
|
+
` : ""}
|
|
1252
|
+
${this.options.showPlaybackSpeed ? `
|
|
1253
|
+
<div class="waveform-speed">
|
|
1254
|
+
<button class="speed-btn" aria-label="${escapeHtml(this.options.speedLabel)}" aria-haspopup="menu" aria-expanded="false">
|
|
1255
|
+
<span class="speed-value">1x</span>
|
|
1256
|
+
</button>
|
|
1257
|
+
<div class="speed-menu" role="menu" aria-label="${escapeHtml(this.options.speedLabel)}" style="display: none;">
|
|
1258
|
+
${this.options.playbackRates.map(
|
|
1259
|
+
(rate) => `<button class="speed-option" role="menuitemradio" tabindex="-1" aria-checked="false" data-rate="${rate}">${rate}x</button>`
|
|
1260
|
+
).join("")}
|
|
1261
|
+
</div>
|
|
1262
|
+
</div>
|
|
1263
|
+
` : ""}
|
|
1264
|
+
${this.options.showTime ? `
|
|
1265
|
+
<span class="waveform-time">
|
|
1266
|
+
<span class="time-current">0:00</span> / <span class="time-total">0:00</span>
|
|
1267
|
+
</span>
|
|
1268
|
+
` : ""}
|
|
1269
|
+
</div>
|
|
1270
|
+
</div>
|
|
1271
|
+
` : "";
|
|
1272
|
+
this.container.innerHTML = `
|
|
1273
|
+
<div class="waveform-player-inner">
|
|
1274
|
+
<div class="waveform-body">
|
|
1275
|
+
<div class="waveform-track waveform-align-${buttonAlign}">
|
|
1276
|
+
${buttonHTML}
|
|
1277
|
+
|
|
1278
|
+
<div class="waveform-container">
|
|
1279
|
+
<canvas></canvas>
|
|
1280
|
+
<div class="waveform-markers"></div>
|
|
1281
|
+
<div class="waveform-loading" style="display:none;"></div>
|
|
1282
|
+
<div class="waveform-error" style="display:none;" role="alert">
|
|
1283
|
+
<span class="waveform-error-text">${escapeHtml(this.options.errorText)}</span>
|
|
1284
|
+
</div>
|
|
1285
|
+
</div>
|
|
1286
|
+
</div>
|
|
1287
|
+
|
|
1288
|
+
${infoHTML}
|
|
1289
|
+
</div>
|
|
1290
|
+
</div>
|
|
1291
|
+
`;
|
|
1292
|
+
this.playBtn = this.container.querySelector(".waveform-btn");
|
|
1293
|
+
this.canvas = this.container.querySelector("canvas");
|
|
1294
|
+
this.ctx = this.canvas.getContext("2d");
|
|
1295
|
+
this.titleEl = this.container.querySelector(".waveform-title");
|
|
1296
|
+
this.artistEl = this.container.querySelector(".waveform-artist");
|
|
1297
|
+
this.artworkEl = this.container.querySelector(".waveform-artwork, .waveform-btn-artwork");
|
|
1298
|
+
this.bindArtworkFallback(this.artworkEl);
|
|
1299
|
+
this.currentTimeEl = this.container.querySelector(".time-current");
|
|
1300
|
+
this.totalTimeEl = this.container.querySelector(".time-total");
|
|
1301
|
+
this.bpmEl = this.container.querySelector(".waveform-bpm");
|
|
1302
|
+
this.bpmValueEl = this.container.querySelector(".bpm-value");
|
|
1303
|
+
this.loadingEl = this.container.querySelector(".waveform-loading");
|
|
1304
|
+
this.errorEl = this.container.querySelector(".waveform-error");
|
|
1305
|
+
this.markersContainer = this.container.querySelector(".waveform-markers");
|
|
1306
|
+
this.speedBtn = this.container.querySelector(".speed-btn");
|
|
1307
|
+
this.speedMenu = this.container.querySelector(".speed-menu");
|
|
1308
|
+
this.resizeCanvas();
|
|
1309
|
+
this.updateBPMDisplay();
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Bind the artwork error fallback to an image element.
|
|
1313
|
+
*
|
|
1314
|
+
* @param {HTMLImageElement|null} img - Artwork image element.
|
|
1315
|
+
* @private
|
|
1316
|
+
*/
|
|
1317
|
+
bindArtworkFallback(img) {
|
|
1318
|
+
if (!img) return;
|
|
1319
|
+
img.addEventListener("error", () => {
|
|
1320
|
+
if (!img.src.startsWith("data:")) img.src = ARTWORK_FALLBACK;
|
|
1321
|
+
}, { signal: this._ac.signal });
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Create an artwork image element matching the initial player markup.
|
|
1325
|
+
*
|
|
1326
|
+
* @returns {HTMLImageElement} Artwork image element.
|
|
1327
|
+
* @private
|
|
1328
|
+
*/
|
|
1329
|
+
createArtworkElement() {
|
|
1330
|
+
const img = document.createElement("img");
|
|
1331
|
+
img.className = "waveform-artwork";
|
|
1332
|
+
img.style.width = "40px";
|
|
1333
|
+
img.style.height = "40px";
|
|
1334
|
+
img.style.borderRadius = "4px";
|
|
1335
|
+
img.style.objectFit = "cover";
|
|
1336
|
+
img.style.flexShrink = "0";
|
|
1337
|
+
this.bindArtworkFallback(img);
|
|
1338
|
+
return img;
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Create a play-button artwork image matching the initial player markup.
|
|
1342
|
+
*
|
|
1343
|
+
* Decorative by design — the button already has an accessible name from its
|
|
1344
|
+
* `aria-label`, so the cover is hidden from assistive tech rather than
|
|
1345
|
+
* given a competing one. Sizing and clipping are the stylesheet's job.
|
|
1346
|
+
*
|
|
1347
|
+
* @returns {HTMLImageElement} Play-button artwork image element.
|
|
1348
|
+
* @private
|
|
1349
|
+
*/
|
|
1350
|
+
createButtonArtworkElement() {
|
|
1351
|
+
const img = document.createElement("img");
|
|
1352
|
+
img.className = "waveform-btn-artwork";
|
|
1353
|
+
img.alt = "";
|
|
1354
|
+
img.setAttribute("aria-hidden", "true");
|
|
1355
|
+
this.bindArtworkFallback(img);
|
|
1356
|
+
return img;
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* Create an artist text element matching the initial player markup.
|
|
1360
|
+
*
|
|
1361
|
+
* @returns {HTMLSpanElement} Artist text element.
|
|
1362
|
+
* @private
|
|
1363
|
+
*/
|
|
1364
|
+
createArtistElement() {
|
|
1365
|
+
const span = document.createElement("span");
|
|
1366
|
+
span.className = "waveform-artist";
|
|
1367
|
+
return span;
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* Reconcile artist metadata and markup for the current track.
|
|
1371
|
+
*
|
|
1372
|
+
* @param {string|null} artist - Artist text, or a falsy value to remove it.
|
|
1373
|
+
* @private
|
|
1374
|
+
*/
|
|
1375
|
+
syncArtist(artist) {
|
|
1376
|
+
this.options.artist = artist || null;
|
|
1377
|
+
if (!this.options.showInfo) return;
|
|
1378
|
+
if (!artist) {
|
|
1379
|
+
this.artistEl?.remove();
|
|
1380
|
+
this.artistEl = null;
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
if (!this.artistEl) {
|
|
1384
|
+
const titleEl = this.container.querySelector(".waveform-title");
|
|
1385
|
+
if (!titleEl) return;
|
|
1386
|
+
this.artistEl = this.createArtistElement();
|
|
1387
|
+
titleEl.after(this.artistEl);
|
|
1388
|
+
}
|
|
1389
|
+
this.artistEl.textContent = artist;
|
|
1390
|
+
this.artistEl.style.display = "";
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* Reconcile the play button's artwork image (`artworkPosition: 'button'`).
|
|
1394
|
+
*
|
|
1395
|
+
* Shares {@link bindArtworkFallback} with the info-row image, so a broken
|
|
1396
|
+
* cover degrades to the same placeholder tile in either placement. The
|
|
1397
|
+
* `waveform-btn-has-artwork` class is what turns on the scrim + glyph
|
|
1398
|
+
* treatment, so it tracks the image's presence exactly.
|
|
1399
|
+
*
|
|
1400
|
+
* @param {string|null} artwork - Artwork image URL, or a falsy value to remove it.
|
|
1401
|
+
* @private
|
|
1402
|
+
*/
|
|
1403
|
+
syncButtonArtwork(artwork) {
|
|
1404
|
+
if (!this.playBtn) return;
|
|
1405
|
+
if (!artwork) {
|
|
1406
|
+
this.artworkEl?.remove();
|
|
1407
|
+
this.artworkEl = null;
|
|
1408
|
+
this.playBtn.classList.remove("waveform-btn-has-artwork");
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
if (!this.artworkEl) {
|
|
1412
|
+
this.artworkEl = this.createButtonArtworkElement();
|
|
1413
|
+
this.playBtn.prepend(this.artworkEl);
|
|
1414
|
+
}
|
|
1415
|
+
this.artworkEl.src = artwork;
|
|
1416
|
+
this.playBtn.classList.add("waveform-btn-has-artwork");
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* Reconcile artwork metadata and markup for the current track.
|
|
1420
|
+
*
|
|
1421
|
+
* The image lives in one of two homes depending on `artworkPosition` — the
|
|
1422
|
+
* info row (default) or the play button — and only ever one of them, so a
|
|
1423
|
+
* cover can't render twice.
|
|
1424
|
+
*
|
|
1425
|
+
* @param {string|null} artwork - Artwork image URL, or a falsy value to remove artwork.
|
|
1426
|
+
* @param {string} artworkAlt - Artwork alt text. Info-row placement only:
|
|
1427
|
+
* button artwork is decorative and defers to the button's own label.
|
|
1428
|
+
* @private
|
|
1429
|
+
*/
|
|
1430
|
+
syncArtwork(artwork, artworkAlt = "") {
|
|
1431
|
+
this.options.artwork = artwork || null;
|
|
1432
|
+
this.options.artworkAlt = artworkAlt || "";
|
|
1433
|
+
if (this.options.artworkPosition === "button") {
|
|
1434
|
+
this.syncButtonArtwork(this.options.artwork);
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
if (!this.options.showInfo) return;
|
|
1438
|
+
if (!artwork) {
|
|
1439
|
+
this.artworkEl?.remove();
|
|
1440
|
+
this.artworkEl = null;
|
|
1441
|
+
return;
|
|
1442
|
+
}
|
|
1443
|
+
if (!this.artworkEl) {
|
|
1444
|
+
const textEl = this.container.querySelector(".waveform-text");
|
|
1445
|
+
if (!textEl) return;
|
|
1446
|
+
this.artworkEl = this.createArtworkElement();
|
|
1447
|
+
textEl.before(this.artworkEl);
|
|
1448
|
+
}
|
|
1449
|
+
this.artworkEl.src = artwork;
|
|
1450
|
+
this.artworkEl.alt = artworkAlt || "";
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Create audio element
|
|
1454
|
+
* @private
|
|
1455
|
+
*
|
|
1456
|
+
* No-op in `audioMode: 'external'` — the player has no audio of its
|
|
1457
|
+
* own; an external controller (e.g. WaveformBar) owns playback and
|
|
1458
|
+
* pushes state in via setPlayingState() / setProgress(). The
|
|
1459
|
+
* `this.audio` field stays null in that mode; downstream code must
|
|
1460
|
+
* null-check it.
|
|
1461
|
+
*/
|
|
1462
|
+
createAudio() {
|
|
1463
|
+
if (this.options.audioMode === "external") {
|
|
1464
|
+
this.audio = null;
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
this.audio = new Audio();
|
|
1468
|
+
this.audio.preload = this.options.preload || "metadata";
|
|
1469
|
+
if (this.options.crossOrigin) {
|
|
1470
|
+
this.audio.crossOrigin = this.options.crossOrigin;
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
// ============================================
|
|
1474
|
+
// Feature Initialization
|
|
1475
|
+
// ============================================
|
|
1476
|
+
/**
|
|
1477
|
+
* Apply the configured initial playback rate to the audio element (self
|
|
1478
|
+
* mode only) and, when `showPlaybackSpeed` is enabled, wire up the speed
|
|
1479
|
+
* menu UI via {@link WaveformPlayer#initSpeedControls}.
|
|
1480
|
+
* @private
|
|
1481
|
+
*/
|
|
1482
|
+
initPlaybackSpeed() {
|
|
1483
|
+
if (this.audio && this.options.playbackRate && this.options.playbackRate !== 1) {
|
|
1484
|
+
this.audio.playbackRate = this.options.playbackRate;
|
|
1485
|
+
}
|
|
1486
|
+
if (this.options.showPlaybackSpeed) {
|
|
1487
|
+
this.initSpeedControls();
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* Wire up the playback-speed menu: toggle it open on the speed button,
|
|
1492
|
+
* close it on outside click or Escape (keeping `aria-expanded` on the
|
|
1493
|
+
* trigger in sync), and apply the chosen rate when a `.speed-option` is
|
|
1494
|
+
* clicked, returning focus to the trigger. All listeners are registered against the
|
|
1495
|
+
* instance `AbortController` signal so {@link WaveformPlayer#destroy} tears
|
|
1496
|
+
* them down. No-op if the speed elements are absent.
|
|
1497
|
+
* @private
|
|
1498
|
+
*/
|
|
1499
|
+
initSpeedControls() {
|
|
1500
|
+
const speedBtn = this.container.querySelector(".speed-btn");
|
|
1501
|
+
const speedMenu = this.container.querySelector(".speed-menu");
|
|
1502
|
+
if (!speedBtn || !speedMenu) return;
|
|
1503
|
+
const options = () => Array.from(speedMenu.querySelectorAll(".speed-option"));
|
|
1504
|
+
const isOpen = () => speedMenu.style.display !== "none";
|
|
1505
|
+
const setSpeedMenu = (open) => {
|
|
1506
|
+
speedMenu.style.display = open ? "block" : "none";
|
|
1507
|
+
speedBtn.setAttribute("aria-expanded", open ? "true" : "false");
|
|
1508
|
+
if (open) {
|
|
1509
|
+
const opts = options();
|
|
1510
|
+
(opts.find((o) => o.getAttribute("aria-checked") === "true") || opts[0])?.focus();
|
|
1511
|
+
}
|
|
1512
|
+
};
|
|
1513
|
+
const focusOption = (i) => {
|
|
1514
|
+
const opts = options();
|
|
1515
|
+
if (opts.length) opts[(i + opts.length) % opts.length].focus();
|
|
1516
|
+
};
|
|
1517
|
+
const selectOption = (opt) => {
|
|
1518
|
+
this.setPlaybackRate(parseFloat(opt.dataset.rate));
|
|
1519
|
+
setSpeedMenu(false);
|
|
1520
|
+
speedBtn.focus();
|
|
1521
|
+
};
|
|
1522
|
+
speedBtn.addEventListener("click", (e) => {
|
|
1523
|
+
e.stopPropagation();
|
|
1524
|
+
setSpeedMenu(!isOpen());
|
|
1525
|
+
}, { signal: this._ac.signal });
|
|
1526
|
+
document.addEventListener("click", () => setSpeedMenu(false), { signal: this._ac.signal });
|
|
1527
|
+
speedMenu.addEventListener("click", (e) => {
|
|
1528
|
+
e.stopPropagation();
|
|
1529
|
+
const opt = e.target.closest(".speed-option");
|
|
1530
|
+
if (opt) selectOption(opt);
|
|
1531
|
+
}, { signal: this._ac.signal });
|
|
1532
|
+
speedBtn.closest(".waveform-speed")?.addEventListener("keydown", (e) => {
|
|
1533
|
+
const opts = options();
|
|
1534
|
+
const i = opts.indexOf(document.activeElement);
|
|
1535
|
+
if (!isOpen()) {
|
|
1536
|
+
if ((e.key === "ArrowDown" || e.key === "ArrowUp") && document.activeElement === speedBtn) {
|
|
1537
|
+
e.preventDefault();
|
|
1538
|
+
setSpeedMenu(true);
|
|
1539
|
+
}
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
switch (e.key) {
|
|
1543
|
+
case "ArrowDown":
|
|
1544
|
+
e.preventDefault();
|
|
1545
|
+
focusOption(i < 0 ? 0 : i + 1);
|
|
1546
|
+
break;
|
|
1547
|
+
case "ArrowUp":
|
|
1548
|
+
e.preventDefault();
|
|
1549
|
+
focusOption(i < 0 ? opts.length - 1 : i - 1);
|
|
1550
|
+
break;
|
|
1551
|
+
case "Home":
|
|
1552
|
+
e.preventDefault();
|
|
1553
|
+
focusOption(0);
|
|
1554
|
+
break;
|
|
1555
|
+
case "End":
|
|
1556
|
+
e.preventDefault();
|
|
1557
|
+
focusOption(opts.length - 1);
|
|
1558
|
+
break;
|
|
1559
|
+
case "Escape":
|
|
1560
|
+
e.preventDefault();
|
|
1561
|
+
setSpeedMenu(false);
|
|
1562
|
+
speedBtn.focus();
|
|
1563
|
+
break;
|
|
1564
|
+
case "Tab":
|
|
1565
|
+
setSpeedMenu(false);
|
|
1566
|
+
break;
|
|
1567
|
+
}
|
|
1568
|
+
}, { signal: this._ac.signal });
|
|
1569
|
+
this.updateSpeedUI();
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* Enable keyboard transport controls on the container.
|
|
1573
|
+
*
|
|
1574
|
+
* The container is focusable only after it is clicked (it carries
|
|
1575
|
+
* `tabindex="-1"` until then, and clicking steals focus from sibling
|
|
1576
|
+
* players). While focused it handles: digits 0-9 (seek to that tenth of
|
|
1577
|
+
* the track), Space (toggle play), and — in self mode only, since
|
|
1578
|
+
* `this.audio` is null in external mode — arrow keys (seek ±5s, volume
|
|
1579
|
+
* ±0.1) and `m`/`M` (mute). Listeners use the instance abort signal.
|
|
1580
|
+
* @private
|
|
1581
|
+
*/
|
|
1582
|
+
initKeyboardControls() {
|
|
1583
|
+
this.container.setAttribute("tabindex", "-1");
|
|
1584
|
+
this.container.addEventListener("click", (e) => {
|
|
1585
|
+
if (e.target.closest(INTERACTIVE_ELEMENTS)) return;
|
|
1586
|
+
_WaveformPlayer.getAllInstances().forEach((player) => {
|
|
1587
|
+
if (player !== this) {
|
|
1588
|
+
player.container.setAttribute("tabindex", "-1");
|
|
1589
|
+
}
|
|
1590
|
+
});
|
|
1591
|
+
this.container.setAttribute("tabindex", "0");
|
|
1592
|
+
this.container.focus();
|
|
1593
|
+
}, { signal: this._ac.signal });
|
|
1594
|
+
this.container.addEventListener("keydown", (e) => {
|
|
1595
|
+
if (document.activeElement !== this.container) return;
|
|
1596
|
+
const key = e.key;
|
|
1597
|
+
const hasAudio = !!this.audio;
|
|
1598
|
+
const currentTime = hasAudio ? this.audio.currentTime : 0;
|
|
1599
|
+
if (hasAudio && key >= "0" && key <= "9") {
|
|
1600
|
+
e.preventDefault();
|
|
1601
|
+
this.seekToPercent(parseInt(key) / 10);
|
|
1602
|
+
return;
|
|
1603
|
+
}
|
|
1604
|
+
const actions = {
|
|
1605
|
+
" ": () => this.togglePlay()
|
|
1606
|
+
};
|
|
1607
|
+
if (hasAudio) {
|
|
1608
|
+
actions["ArrowLeft"] = () => this.seekTo(clamp(currentTime - 5, 0, this.audio.duration));
|
|
1609
|
+
actions["ArrowRight"] = () => this.seekTo(clamp(currentTime + 5, 0, this.audio.duration));
|
|
1610
|
+
actions["ArrowUp"] = () => this.setVolume(clamp(this.audio.volume + 0.1));
|
|
1611
|
+
actions["ArrowDown"] = () => this.setVolume(clamp(this.audio.volume - 0.1));
|
|
1612
|
+
actions["m"] = actions["M"] = () => this.audio.muted = !this.audio.muted;
|
|
1613
|
+
}
|
|
1614
|
+
if (actions[key]) {
|
|
1615
|
+
e.preventDefault();
|
|
1616
|
+
actions[key]();
|
|
1617
|
+
}
|
|
1618
|
+
}, { signal: this._ac.signal });
|
|
1619
|
+
}
|
|
1620
|
+
/**
|
|
1621
|
+
* Expose the waveform as an accessible, keyboard-operable slider.
|
|
1622
|
+
*
|
|
1623
|
+
* Adds role="slider" + ARIA value attributes to the waveform surface,
|
|
1624
|
+
* makes it focusable in the tab order, and handles the standard slider
|
|
1625
|
+
* keys (arrows, Page Up/Down, Home/End) to seek. Works in both self and
|
|
1626
|
+
* external audio modes. Opt out with `accessibleSeek: false`.
|
|
1627
|
+
* @private
|
|
1628
|
+
*/
|
|
1629
|
+
initSeekControl() {
|
|
1630
|
+
if (!this.options.accessibleSeek) return;
|
|
1631
|
+
this.seekEl = this.container.querySelector(".waveform-container");
|
|
1632
|
+
if (!this.seekEl) return;
|
|
1633
|
+
this.seekEl.setAttribute("role", "slider");
|
|
1634
|
+
this.seekEl.setAttribute("tabindex", "0");
|
|
1635
|
+
this.seekEl.setAttribute("aria-valuemin", "0");
|
|
1636
|
+
this.applySeekLabel();
|
|
1637
|
+
this.updateSeekAccessibility();
|
|
1638
|
+
this.seekEl.addEventListener("keydown", (e) => {
|
|
1639
|
+
if (e.key === " " || e.key === "Spacebar") {
|
|
1640
|
+
e.preventDefault();
|
|
1641
|
+
e.stopPropagation();
|
|
1642
|
+
this.togglePlay();
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
const duration = this.getSeekDuration();
|
|
1646
|
+
if (!duration) return;
|
|
1647
|
+
const current = this.getSeekCurrentTime();
|
|
1648
|
+
let target;
|
|
1649
|
+
switch (e.key) {
|
|
1650
|
+
case "ArrowLeft":
|
|
1651
|
+
case "ArrowDown":
|
|
1652
|
+
target = current - SEEK_STEP_SECONDS;
|
|
1653
|
+
break;
|
|
1654
|
+
case "ArrowRight":
|
|
1655
|
+
case "ArrowUp":
|
|
1656
|
+
target = current + SEEK_STEP_SECONDS;
|
|
1657
|
+
break;
|
|
1658
|
+
case "PageDown":
|
|
1659
|
+
target = current - SEEK_PAGE_SECONDS;
|
|
1660
|
+
break;
|
|
1661
|
+
case "PageUp":
|
|
1662
|
+
target = current + SEEK_PAGE_SECONDS;
|
|
1663
|
+
break;
|
|
1664
|
+
case "Home":
|
|
1665
|
+
target = 0;
|
|
1666
|
+
break;
|
|
1667
|
+
case "End":
|
|
1668
|
+
target = duration;
|
|
1669
|
+
break;
|
|
1670
|
+
default:
|
|
1671
|
+
return;
|
|
1672
|
+
}
|
|
1673
|
+
e.preventDefault();
|
|
1674
|
+
e.stopPropagation();
|
|
1675
|
+
this.seekToSeconds(target);
|
|
1676
|
+
}, { signal: this._ac.signal });
|
|
1677
|
+
}
|
|
1678
|
+
/**
|
|
1679
|
+
* Total seekable duration in seconds, regardless of audio mode.
|
|
1680
|
+
* @returns {number}
|
|
1681
|
+
* @private
|
|
1682
|
+
*/
|
|
1683
|
+
getSeekDuration() {
|
|
1684
|
+
if (this.options.audioMode === "external") {
|
|
1685
|
+
return this._extDuration || 0;
|
|
1686
|
+
}
|
|
1687
|
+
return this.audio && Number.isFinite(this.audio.duration) ? this.audio.duration : 0;
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* Current playback position in seconds, regardless of audio mode.
|
|
1691
|
+
* @returns {number}
|
|
1692
|
+
* @private
|
|
1693
|
+
*/
|
|
1694
|
+
getSeekCurrentTime() {
|
|
1695
|
+
if (this.options.audioMode === "external") {
|
|
1696
|
+
return this.progress * (this._extDuration || 0);
|
|
1697
|
+
}
|
|
1698
|
+
return this.audio && Number.isFinite(this.audio.currentTime) ? this.audio.currentTime : 0;
|
|
1699
|
+
}
|
|
1700
|
+
/**
|
|
1701
|
+
* Seek the slider to an absolute time, clamped to the track length.
|
|
1702
|
+
*
|
|
1703
|
+
* In self mode this defers to {@link WaveformPlayer#seekTo}. In external
|
|
1704
|
+
* mode it dispatches a cancelable `waveformplayer:request-seek` event with
|
|
1705
|
+
* the target percentage; if the controller doesn't `preventDefault()`, the
|
|
1706
|
+
* local progress/visual is updated optimistically. Either way the ARIA
|
|
1707
|
+
* slider values are refreshed.
|
|
1708
|
+
* @param {number} seconds - Target time in seconds.
|
|
1709
|
+
* @private
|
|
1710
|
+
* @fires WaveformPlayer#waveformplayer:request-seek
|
|
1711
|
+
*/
|
|
1712
|
+
seekToSeconds(seconds) {
|
|
1713
|
+
const duration = this.getSeekDuration();
|
|
1714
|
+
if (!duration) return;
|
|
1715
|
+
const clamped = clamp(seconds, 0, duration);
|
|
1716
|
+
if (this.options.audioMode === "external") {
|
|
1717
|
+
this._requestSeek(clamped / duration);
|
|
1718
|
+
this.updateSeekAccessibility();
|
|
1719
|
+
return;
|
|
1720
|
+
}
|
|
1721
|
+
this.seekTo(clamped);
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* Set the slider's accessible name from `seekLabel`, falling back to the
|
|
1725
|
+
* track title, then a generic 'Seek'. No-op if the slider isn't present.
|
|
1726
|
+
* @param {string} [title=this.options.title] - Track title to fall back to
|
|
1727
|
+
* when `seekLabel` is not set.
|
|
1728
|
+
* @private
|
|
1729
|
+
*/
|
|
1730
|
+
applySeekLabel(title = this.options.title) {
|
|
1731
|
+
if (!this.seekEl) return;
|
|
1732
|
+
const label = this.options.seekLabel || title || "Seek";
|
|
1733
|
+
this.seekEl.setAttribute("aria-label", label);
|
|
1734
|
+
}
|
|
1735
|
+
/**
|
|
1736
|
+
* Keep the slider's ARIA value attributes in sync with playback.
|
|
1737
|
+
* @private
|
|
1738
|
+
*/
|
|
1739
|
+
updateSeekAccessibility() {
|
|
1740
|
+
if (!this.seekEl) return;
|
|
1741
|
+
const duration = this.getSeekDuration();
|
|
1742
|
+
const current = Math.min(this.getSeekCurrentTime(), duration);
|
|
1743
|
+
this.seekEl.setAttribute("aria-valuemax", String(Math.round(duration)));
|
|
1744
|
+
this.seekEl.setAttribute("aria-valuenow", String(Math.round(current)));
|
|
1745
|
+
this.seekEl.setAttribute(
|
|
1746
|
+
"aria-valuetext",
|
|
1747
|
+
formatSeekValueText(
|
|
1748
|
+
this.options.seekValueText || "%1$s of %2$s",
|
|
1749
|
+
formatTime(current),
|
|
1750
|
+
formatTime(duration)
|
|
1751
|
+
)
|
|
1752
|
+
);
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* Initialize Media Session API for system media controls
|
|
1756
|
+
* @private
|
|
1757
|
+
*/
|
|
1758
|
+
initMediaSession() {
|
|
1759
|
+
if (!("mediaSession" in navigator) || !this.options.enableMediaSession) return;
|
|
1760
|
+
if (!this.audio) return;
|
|
1761
|
+
this._applyMediaMetadata();
|
|
1762
|
+
navigator.mediaSession.setActionHandler("play", () => this.play());
|
|
1763
|
+
navigator.mediaSession.setActionHandler("pause", () => this.pause());
|
|
1764
|
+
navigator.mediaSession.setActionHandler("seekbackward", () => {
|
|
1765
|
+
this.seekTo(clamp(this.audio.currentTime - 10, 0, this.audio.duration));
|
|
1766
|
+
});
|
|
1767
|
+
navigator.mediaSession.setActionHandler("seekforward", () => {
|
|
1768
|
+
this.seekTo(clamp(this.audio.currentTime + 10, 0, this.audio.duration));
|
|
1769
|
+
});
|
|
1770
|
+
navigator.mediaSession.setActionHandler("seekto", (details) => {
|
|
1771
|
+
if (details.seekTime !== null) {
|
|
1772
|
+
this.seekTo(details.seekTime);
|
|
1773
|
+
}
|
|
1774
|
+
});
|
|
1775
|
+
const onNext = this.options.onNextTrack, onPrev = this.options.onPreviousTrack;
|
|
1776
|
+
try {
|
|
1777
|
+
navigator.mediaSession.setActionHandler("nexttrack", typeof onNext === "function" ? () => onNext(this) : null);
|
|
1778
|
+
} catch (e) {
|
|
1779
|
+
}
|
|
1780
|
+
try {
|
|
1781
|
+
navigator.mediaSession.setActionHandler("previoustrack", typeof onPrev === "function" ? () => onPrev(this) : null);
|
|
1782
|
+
} catch (e) {
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
/**
|
|
1786
|
+
* Publish the current track's Media Session metadata (lock-screen /
|
|
1787
|
+
* Now-Playing title, artist, album, artwork). Idempotent — safe to re-call.
|
|
1788
|
+
* @private
|
|
1789
|
+
*/
|
|
1790
|
+
_applyMediaMetadata() {
|
|
1791
|
+
if (!("mediaSession" in navigator) || !this.options.enableMediaSession) return;
|
|
1792
|
+
navigator.mediaSession.metadata = new MediaMetadata({
|
|
1793
|
+
title: this.options.title || this.options.unknownTrackText,
|
|
1794
|
+
artist: this.options.artist || "",
|
|
1795
|
+
album: this.options.album || "",
|
|
1796
|
+
artwork: this.options.artwork ? [
|
|
1797
|
+
{ src: this.options.artwork, sizes: "512x512", type: "image/jpeg" }
|
|
1798
|
+
] : []
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
/**
|
|
1802
|
+
* Sync Media Session playback state + scrubber position on play/pause. iOS
|
|
1803
|
+
* ignores metadata set before the media is active, so we re-assert it on
|
|
1804
|
+
* play — that's what fixes the blank lock-screen card on mobile.
|
|
1805
|
+
* @param {'playing'|'paused'} state
|
|
1806
|
+
* @private
|
|
1807
|
+
*/
|
|
1808
|
+
_updateMediaSession(state) {
|
|
1809
|
+
if (!("mediaSession" in navigator) || !this.options.enableMediaSession || !this.audio) return;
|
|
1810
|
+
try {
|
|
1811
|
+
if (state === "playing") this.initMediaSession();
|
|
1812
|
+
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
|
+
}
|
|
1821
|
+
} catch (e) {
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
// ============================================
|
|
1825
|
+
// Event Binding
|
|
1826
|
+
// ============================================
|
|
1827
|
+
/**
|
|
1828
|
+
* Bind the core interaction listeners: play-button click, the `<audio>`
|
|
1829
|
+
* media events (self mode only — external mode is fed state via
|
|
1830
|
+
* {@link WaveformPlayer#setPlayingState}/{@link WaveformPlayer#setProgress}),
|
|
1831
|
+
* canvas click-to-seek, and a debounced window-resize redraw.
|
|
1832
|
+
* @private
|
|
1833
|
+
*/
|
|
1834
|
+
bindEvents() {
|
|
1835
|
+
if (this.playBtn) {
|
|
1836
|
+
this.playBtn.addEventListener("click", () => this.togglePlay());
|
|
1837
|
+
}
|
|
1838
|
+
if (this.audio) {
|
|
1839
|
+
this.audio.addEventListener("loadstart", () => this.setLoading(true));
|
|
1840
|
+
this.audio.addEventListener("loadedmetadata", () => this.onMetadataLoaded());
|
|
1841
|
+
this.audio.addEventListener("canplay", () => this.setLoading(false));
|
|
1842
|
+
this.audio.addEventListener("play", () => this.onPlay());
|
|
1843
|
+
this.audio.addEventListener("pause", () => this.onPause());
|
|
1844
|
+
this.audio.addEventListener("ended", () => this.onEnded());
|
|
1845
|
+
this.audio.addEventListener("error", (e) => this.onError(e));
|
|
1846
|
+
}
|
|
1847
|
+
this.canvas.addEventListener("click", (e) => this.handleCanvasClick(e));
|
|
1848
|
+
this._dragging = false;
|
|
1849
|
+
this._seekHover = false;
|
|
1850
|
+
this._handleNear = false;
|
|
1851
|
+
this.canvas.addEventListener("pointerenter", () => {
|
|
1852
|
+
this._seekHover = true;
|
|
1853
|
+
this.drawWaveform();
|
|
1854
|
+
this._updateSeekHandle();
|
|
1855
|
+
});
|
|
1856
|
+
this.canvas.addEventListener("pointerleave", () => {
|
|
1857
|
+
this._seekHover = false;
|
|
1858
|
+
this._handleNear = false;
|
|
1859
|
+
if (!this._dragging) this._hideHoverTip();
|
|
1860
|
+
this.drawWaveform();
|
|
1861
|
+
this._updateSeekHandle();
|
|
1862
|
+
});
|
|
1863
|
+
this.canvas.addEventListener("pointerdown", (e) => {
|
|
1864
|
+
if (e.pointerType === "mouse" && e.button !== 0) return;
|
|
1865
|
+
this._dragging = true;
|
|
1866
|
+
try {
|
|
1867
|
+
this.canvas.setPointerCapture(e.pointerId);
|
|
1868
|
+
} catch (err) {
|
|
1869
|
+
}
|
|
1870
|
+
this._scrubTo(e.clientX);
|
|
1871
|
+
});
|
|
1872
|
+
this.canvas.addEventListener("pointermove", (e) => {
|
|
1873
|
+
if (this._dragging) {
|
|
1874
|
+
this._scrubTo(e.clientX);
|
|
1875
|
+
return;
|
|
1876
|
+
}
|
|
1877
|
+
const rect = this.canvas.getBoundingClientRect();
|
|
1878
|
+
if (rect.width) {
|
|
1879
|
+
this._handleNear = Math.abs(e.clientX - rect.left - this.progress * rect.width) <= 10;
|
|
1880
|
+
this._updateSeekHandle();
|
|
1881
|
+
}
|
|
1882
|
+
});
|
|
1883
|
+
const endDrag = (e) => {
|
|
1884
|
+
if (!this._dragging) return;
|
|
1885
|
+
this._dragging = false;
|
|
1886
|
+
this._suppressClick = true;
|
|
1887
|
+
try {
|
|
1888
|
+
this.canvas.releasePointerCapture(e.pointerId);
|
|
1889
|
+
} catch (err) {
|
|
1890
|
+
}
|
|
1891
|
+
this._seekFromPointer(e.clientX);
|
|
1892
|
+
if (!this._seekHover && !this.options.showHoverTime) this._hideHoverTip();
|
|
1893
|
+
this._updateSeekHandle();
|
|
1894
|
+
};
|
|
1895
|
+
this.canvas.addEventListener("pointerup", endDrag);
|
|
1896
|
+
this.canvas.addEventListener("pointercancel", endDrag);
|
|
1897
|
+
this.setupHoverTime();
|
|
1898
|
+
this.setupSeekHandle();
|
|
1899
|
+
this.resizeHandler = debounce(() => this.resizeCanvas(), 100);
|
|
1900
|
+
window.addEventListener("resize", this.resizeHandler);
|
|
1901
|
+
}
|
|
1902
|
+
/**
|
|
1903
|
+
* Observe the canvas's parent element for size changes and re-fit the
|
|
1904
|
+
* canvas on each one. No-op where `ResizeObserver` is unavailable.
|
|
1905
|
+
* @private
|
|
1906
|
+
*/
|
|
1907
|
+
setupResizeObserver() {
|
|
1908
|
+
if ("ResizeObserver" in window) {
|
|
1909
|
+
this.resizeObserver = new ResizeObserver(() => {
|
|
1910
|
+
this.resizeCanvas();
|
|
1911
|
+
});
|
|
1912
|
+
if (this.canvas?.parentElement) {
|
|
1913
|
+
this.resizeObserver.observe(this.canvas.parentElement);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
// ============================================
|
|
1918
|
+
// Audio Loading
|
|
1919
|
+
// ============================================
|
|
1920
|
+
/**
|
|
1921
|
+
* Load an audio source: set the title, fetch/generate the waveform peaks,
|
|
1922
|
+
* draw them, render markers, and initialise Media Session.
|
|
1923
|
+
*
|
|
1924
|
+
* In self mode the `<audio>` src is assigned and the method awaits
|
|
1925
|
+
* `loadedmetadata` before proceeding. In external mode there is no audio
|
|
1926
|
+
* element, so the src/metadata step is skipped and only the visualization
|
|
1927
|
+
* is built (duration/time come from the controller via
|
|
1928
|
+
* {@link WaveformPlayer#setProgress}). The title and the seek slider's
|
|
1929
|
+
* accessible name are written *before* the metadata wait, as are peaks
|
|
1930
|
+
* supplied via the `waveform` option — none of them need anything from the
|
|
1931
|
+
* 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.
|
|
1935
|
+
* @param {string} url - Audio URL.
|
|
1936
|
+
* @returns {Promise<void>} Resolves once loading settles (errors are caught
|
|
1937
|
+
* internally and surfaced through {@link WaveformPlayer#onError}).
|
|
1938
|
+
*/
|
|
1939
|
+
async load(url) {
|
|
1940
|
+
try {
|
|
1941
|
+
this.setLoading(true);
|
|
1942
|
+
this.progress = 0;
|
|
1943
|
+
this.hasError = false;
|
|
1944
|
+
this.container.classList.remove("waveform-is-placeholder");
|
|
1945
|
+
const hasInlinePeaks = !!this.options.waveform;
|
|
1946
|
+
if (hasInlinePeaks) {
|
|
1947
|
+
this.setWaveformData(this.options.waveform);
|
|
1948
|
+
}
|
|
1949
|
+
const title = this.options.title || extractTitleFromUrl(url);
|
|
1950
|
+
if (this.titleEl) {
|
|
1951
|
+
this.titleEl.textContent = title;
|
|
1952
|
+
}
|
|
1953
|
+
this.applySeekLabel(title);
|
|
1954
|
+
if (this.audio) {
|
|
1955
|
+
this.audio.src = url;
|
|
1956
|
+
if (this.audio.preload !== "none") {
|
|
1957
|
+
await new Promise((resolve, reject) => {
|
|
1958
|
+
const metadataHandler = () => {
|
|
1959
|
+
this.audio.removeEventListener("loadedmetadata", metadataHandler);
|
|
1960
|
+
this.audio.removeEventListener("error", errorHandler);
|
|
1961
|
+
resolve();
|
|
1962
|
+
};
|
|
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);
|
|
1970
|
+
});
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
if (!hasInlinePeaks) {
|
|
1974
|
+
try {
|
|
1975
|
+
const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
|
|
1976
|
+
this.waveformData = result.peaks;
|
|
1977
|
+
if (result.bpm) {
|
|
1978
|
+
this.detectedBPM = result.bpm;
|
|
1979
|
+
this.updateBPMDisplay();
|
|
1980
|
+
}
|
|
1981
|
+
} catch (error) {
|
|
1982
|
+
console.warn("[WaveformPlayer] Using placeholder waveform:", error);
|
|
1983
|
+
this.waveformData = generatePlaceholderWaveform(this.options.samples);
|
|
1984
|
+
this.container.classList.add("waveform-is-placeholder");
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
this.drawWaveform();
|
|
1988
|
+
this.renderMarkers();
|
|
1989
|
+
if (this.options.onLoad) {
|
|
1990
|
+
this.options.onLoad(this);
|
|
1991
|
+
}
|
|
1992
|
+
} catch (error) {
|
|
1993
|
+
this.onError(error);
|
|
1994
|
+
} finally {
|
|
1995
|
+
this.setLoading(false);
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
/**
|
|
1999
|
+
* Swap the player to a new track at runtime.
|
|
2000
|
+
*
|
|
2001
|
+
* Pauses any current playback, fully resets the audio element (self mode),
|
|
2002
|
+
* clears error/marker/progress state, merges the new metadata into
|
|
2003
|
+
* `this.options`, updates the artist/artwork DOM, then calls
|
|
2004
|
+
* {@link WaveformPlayer#load}. Auto-plays the new track unless
|
|
2005
|
+
* `options.autoplay === false`.
|
|
2006
|
+
* @param {string} url - Audio URL.
|
|
2007
|
+
* @param {string|null} [title=null] - Track title; keeps the existing
|
|
2008
|
+
* title when null.
|
|
2009
|
+
* @param {string|null} [artist=null] - Track artist; pass `''` to hide
|
|
2010
|
+
* the artist row, or null to keep the existing one.
|
|
2011
|
+
* @param {Object} [options={}] - Additional options to merge (e.g.
|
|
2012
|
+
* `preload`, `artwork`, `artworkAlt`, `markers`, `autoplay`).
|
|
2013
|
+
* @returns {Promise<void>}
|
|
2014
|
+
*/
|
|
2015
|
+
async loadTrack(url, title = null, artist = null, options = {}) {
|
|
2016
|
+
const hasArtworkOption = Object.prototype.hasOwnProperty.call(options, "artwork");
|
|
2017
|
+
const hasArtworkAltOption = Object.prototype.hasOwnProperty.call(options, "artworkAlt");
|
|
2018
|
+
if (this.isPlaying) {
|
|
2019
|
+
this.pause();
|
|
2020
|
+
}
|
|
2021
|
+
if (this.audio) {
|
|
2022
|
+
this.audio.src = "";
|
|
2023
|
+
this.audio.load();
|
|
2024
|
+
}
|
|
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 = [];
|
|
2037
|
+
this.options = normalizeOptions(mergeOptions(this.options, {
|
|
2038
|
+
url,
|
|
2039
|
+
title: title === null ? this.options.title : title,
|
|
2040
|
+
artist: artist === null ? this.options.artist : artist,
|
|
2041
|
+
...options
|
|
2042
|
+
}));
|
|
2043
|
+
if (hasArtworkOption) {
|
|
2044
|
+
this.options.artwork = options.artwork || null;
|
|
2045
|
+
}
|
|
2046
|
+
if (hasArtworkAltOption) {
|
|
2047
|
+
this.options.artworkAlt = options.artworkAlt || "";
|
|
2048
|
+
} else if (hasArtworkOption) {
|
|
2049
|
+
this.options.artworkAlt = this.options.artwork ? DEFAULT_OPTIONS.artworkAlt : "";
|
|
2050
|
+
}
|
|
2051
|
+
if (options.preload && this.audio) {
|
|
2052
|
+
this.audio.preload = this.options.preload;
|
|
2053
|
+
}
|
|
2054
|
+
if (options.crossOrigin && this.audio) {
|
|
2055
|
+
this.audio.crossOrigin = this.options.crossOrigin;
|
|
2056
|
+
}
|
|
2057
|
+
if (artist !== null) {
|
|
2058
|
+
this.syncArtist(artist);
|
|
2059
|
+
}
|
|
2060
|
+
if (hasArtworkOption || hasArtworkAltOption) {
|
|
2061
|
+
this.syncArtwork(
|
|
2062
|
+
hasArtworkOption ? options.artwork : this.options.artwork,
|
|
2063
|
+
hasArtworkAltOption ? options.artworkAlt : this.options.artworkAlt
|
|
2064
|
+
);
|
|
2065
|
+
}
|
|
2066
|
+
this.options.markers = options.markers ? normalizeMarkers(options.markers) : [];
|
|
2067
|
+
this.options.waveform = options.waveform || null;
|
|
2068
|
+
await this.load(url);
|
|
2069
|
+
if (options.autoplay !== false) {
|
|
2070
|
+
this.play()?.catch(() => {
|
|
2071
|
+
});
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
// ============================================
|
|
2075
|
+
// Visualization
|
|
2076
|
+
// ============================================
|
|
2077
|
+
/**
|
|
2078
|
+
* Normalise externally-supplied waveform data into `this.waveformData` and
|
|
2079
|
+
* redraw.
|
|
2080
|
+
*
|
|
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.
|
|
2085
|
+
* @param {string|number[]} data - Peaks as an array, a JSON/CSV string, or
|
|
2086
|
+
* a URL to a `.json` peaks file.
|
|
2087
|
+
* @private
|
|
2088
|
+
*/
|
|
2089
|
+
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 || [];
|
|
2093
|
+
if (json.markers && !this.options.markers?.length) {
|
|
2094
|
+
this.options.markers = normalizeMarkers(json.markers);
|
|
2095
|
+
this.renderMarkers();
|
|
2096
|
+
}
|
|
2097
|
+
this.drawWaveform();
|
|
2098
|
+
}).catch(() => {
|
|
2099
|
+
});
|
|
2100
|
+
return;
|
|
2101
|
+
}
|
|
2102
|
+
this.waveformData = toNumberArray(data, { fallback: [] });
|
|
2103
|
+
this.drawWaveform();
|
|
2104
|
+
}
|
|
2105
|
+
/**
|
|
2106
|
+
* Render the current waveform + progress to the canvas via the shared
|
|
2107
|
+
* {@link draw} routine, passing the resolved style and colours. No-op
|
|
2108
|
+
* before the context exists or while there is no peak data.
|
|
2109
|
+
* @private
|
|
2110
|
+
*/
|
|
2111
|
+
drawWaveform() {
|
|
2112
|
+
if (!this.ctx || this.waveformData.length === 0) return;
|
|
2113
|
+
draw(this.ctx, this.canvas, this.waveformData, this.progress, {
|
|
2114
|
+
...this.options,
|
|
2115
|
+
waveformStyle: this.options.waveformStyle || "bars",
|
|
2116
|
+
color: this.options.waveformColor,
|
|
2117
|
+
progressColor: this.options.progressColor,
|
|
2118
|
+
seekActive: this._seekHover || this._dragging
|
|
2119
|
+
});
|
|
2120
|
+
}
|
|
2121
|
+
/**
|
|
2122
|
+
* Re-fit the canvas backing store to its parent's width and the configured
|
|
2123
|
+
* height, scaled by the device pixel ratio for crisp rendering, then
|
|
2124
|
+
* redraw. Guards against running after destruction.
|
|
2125
|
+
* @private
|
|
2126
|
+
*/
|
|
2127
|
+
resizeCanvas() {
|
|
2128
|
+
if (!this.canvas || this.isDestroying) {
|
|
2129
|
+
return;
|
|
2130
|
+
}
|
|
2131
|
+
const dpr = window.devicePixelRatio || 1;
|
|
2132
|
+
const rect = this.canvas.parentElement.getBoundingClientRect();
|
|
2133
|
+
this.canvas.width = rect.width * dpr;
|
|
2134
|
+
this.canvas.height = this.options.height * dpr;
|
|
2135
|
+
this.canvas.parentElement.style.height = this.options.height + "px";
|
|
2136
|
+
this.drawWaveform();
|
|
2137
|
+
}
|
|
2138
|
+
/**
|
|
2139
|
+
* Render the configured cue markers as positioned, clickable buttons over
|
|
2140
|
+
* the waveform.
|
|
2141
|
+
*
|
|
2142
|
+
* Clears any existing markers first, then bails out unless `showMarkers` is
|
|
2143
|
+
* on, markers exist, and a duration is known (via the mode-agnostic
|
|
2144
|
+
* {@link WaveformPlayer#getSeekDuration}). Each marker is placed by its
|
|
2145
|
+
* time-as-percentage, carries a tooltip and ARIA label, and seeks on click
|
|
2146
|
+
* (also starting playback when `playOnSeek` is set and currently paused).
|
|
2147
|
+
* Markers past the track duration are skipped with a warning.
|
|
2148
|
+
* @private
|
|
2149
|
+
*/
|
|
2150
|
+
renderMarkers() {
|
|
2151
|
+
if (!this.markersContainer) return;
|
|
2152
|
+
this.markersContainer.innerHTML = "";
|
|
2153
|
+
this._activeMarkerIndex = -1;
|
|
2154
|
+
clearTimeout(this._markerLabelTimer);
|
|
2155
|
+
if (!this.options.showMarkers || !this.options.markers?.length) return;
|
|
2156
|
+
const duration = this.getSeekDuration();
|
|
2157
|
+
if (!duration) {
|
|
2158
|
+
return;
|
|
2159
|
+
}
|
|
2160
|
+
this.options.markers.forEach((marker, index) => {
|
|
2161
|
+
if (marker.time > duration) {
|
|
2162
|
+
console.warn(`[WaveformPlayer] Marker "${marker.label}" at ${marker.time}s exceeds audio duration of ${duration}s`);
|
|
2163
|
+
return;
|
|
2164
|
+
}
|
|
2165
|
+
const position = marker.time / duration * 100;
|
|
2166
|
+
const markerEl = document.createElement("button");
|
|
2167
|
+
markerEl.className = "waveform-marker";
|
|
2168
|
+
markerEl.style.left = `${position}%`;
|
|
2169
|
+
markerEl.style.backgroundColor = marker.color || "rgba(255, 255, 255, 0.5)";
|
|
2170
|
+
markerEl.setAttribute("aria-label", marker.label);
|
|
2171
|
+
markerEl.setAttribute("data-time", marker.time);
|
|
2172
|
+
const tooltip = document.createElement("span");
|
|
2173
|
+
tooltip.className = "waveform-marker-tooltip";
|
|
2174
|
+
tooltip.textContent = marker.label;
|
|
2175
|
+
markerEl.appendChild(tooltip);
|
|
2176
|
+
markerEl.addEventListener("click", (e) => {
|
|
2177
|
+
e.stopPropagation();
|
|
2178
|
+
this.seekTo(marker.time);
|
|
2179
|
+
if (this.options.playOnSeek && !this.isPlaying) {
|
|
2180
|
+
this.play();
|
|
2181
|
+
}
|
|
2182
|
+
});
|
|
2183
|
+
this.markersContainer.appendChild(markerEl);
|
|
2184
|
+
});
|
|
2185
|
+
}
|
|
2186
|
+
/**
|
|
2187
|
+
* Highlight the marker at `index` (toggling an `active` class) and clear
|
|
2188
|
+
* the rest. Pass `null` to clear all. Lets an external controller (e.g. a
|
|
2189
|
+
* DJ bar) reflect the current section without reaching into the player's
|
|
2190
|
+
* private marker DOM.
|
|
2191
|
+
* @param {number|null} index - Marker index to activate, or `null` to clear.
|
|
2192
|
+
*/
|
|
2193
|
+
setActiveMarker(index) {
|
|
2194
|
+
if (!this.markersContainer) return;
|
|
2195
|
+
const markers = this.markersContainer.querySelectorAll(".waveform-marker");
|
|
2196
|
+
markers.forEach((el, i) => el.classList.toggle("active", i === index));
|
|
2197
|
+
}
|
|
2198
|
+
/**
|
|
2199
|
+
* Highlight the marker the playhead has most recently passed — the rendered
|
|
2200
|
+
* marker with the greatest `time` ≤ the current time — and reveal its label.
|
|
2201
|
+
* Driven from the progress loop; a no-op when there are no markers. Reuses
|
|
2202
|
+
* {@link WaveformPlayer#setActiveMarker}, and only re-applies when the active
|
|
2203
|
+
* marker actually changes.
|
|
2204
|
+
* @private
|
|
2205
|
+
*/
|
|
2206
|
+
updateActiveMarker() {
|
|
2207
|
+
if (!this.markersContainer) return;
|
|
2208
|
+
const els = this.markersContainer.querySelectorAll(".waveform-marker");
|
|
2209
|
+
if (!els.length) return;
|
|
2210
|
+
const dur = this.getSeekDuration();
|
|
2211
|
+
const t = dur ? this.progress * dur : 0;
|
|
2212
|
+
let active = -1;
|
|
2213
|
+
let best = -Infinity;
|
|
2214
|
+
els.forEach((el, i) => {
|
|
2215
|
+
const mt = parseFloat(el.getAttribute("data-time"));
|
|
2216
|
+
if (Number.isFinite(mt) && mt <= t + 0.05 && mt > best) {
|
|
2217
|
+
best = mt;
|
|
2218
|
+
active = i;
|
|
2219
|
+
}
|
|
2220
|
+
});
|
|
2221
|
+
if (active !== this._activeMarkerIndex) {
|
|
2222
|
+
this._activeMarkerIndex = active;
|
|
2223
|
+
this.setActiveMarker(active);
|
|
2224
|
+
clearTimeout(this._markerLabelTimer);
|
|
2225
|
+
els.forEach((el, i) => el.classList.toggle("show-label", i === active));
|
|
2226
|
+
if (active >= 0) {
|
|
2227
|
+
this._markerLabelTimer = setTimeout(() => {
|
|
2228
|
+
this.markersContainer?.querySelectorAll(".waveform-marker").forEach((el) => el.classList.remove("show-label"));
|
|
2229
|
+
}, 2500);
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
/**
|
|
2234
|
+
* Build the time tooltip that follows the pointer over the waveform. The
|
|
2235
|
+
* element is always created so **drag-scrub** can show the time you're
|
|
2236
|
+
* dragging to; the *hover* reveal is gated on `showHoverTime`. Works in both
|
|
2237
|
+
* self and external modes (it only needs {@link WaveformPlayer#getSeekDuration}).
|
|
2238
|
+
* @private
|
|
2239
|
+
*/
|
|
2240
|
+
setupHoverTime() {
|
|
2241
|
+
if (!this.seekEl) return;
|
|
2242
|
+
const tip = document.createElement("div");
|
|
2243
|
+
tip.className = "waveform-hover-time";
|
|
2244
|
+
tip.setAttribute("aria-hidden", "true");
|
|
2245
|
+
this.seekEl.appendChild(tip);
|
|
2246
|
+
this.hoverTimeEl = tip;
|
|
2247
|
+
if (!this.options.showHoverTime) return;
|
|
2248
|
+
this.seekEl.addEventListener("pointermove", (e) => {
|
|
2249
|
+
if (!this._dragging) this._updateHoverTip(e.clientX);
|
|
2250
|
+
});
|
|
2251
|
+
this.seekEl.addEventListener("pointerleave", () => {
|
|
2252
|
+
if (!this._dragging) this._hideHoverTip();
|
|
2253
|
+
});
|
|
2254
|
+
}
|
|
2255
|
+
/**
|
|
2256
|
+
* Position + fill the hover-time tooltip for a given client-X. Shared by
|
|
2257
|
+
* hover and drag-scrub. No-op when the tooltip isn't enabled
|
|
2258
|
+
* (`showHoverTime` off).
|
|
2259
|
+
* @param {number} clientX - Pointer client-X coordinate.
|
|
2260
|
+
* @private
|
|
2261
|
+
*/
|
|
2262
|
+
_updateHoverTip(clientX) {
|
|
2263
|
+
const tip = this.hoverTimeEl;
|
|
2264
|
+
if (!tip) return;
|
|
2265
|
+
const dur = this.getSeekDuration();
|
|
2266
|
+
if (!dur) {
|
|
2267
|
+
tip.style.opacity = "0";
|
|
2268
|
+
return;
|
|
2269
|
+
}
|
|
2270
|
+
const rect = this.canvas.getBoundingClientRect();
|
|
2271
|
+
const pct = clamp((clientX - rect.left) / rect.width);
|
|
2272
|
+
tip.textContent = formatTime(pct * dur);
|
|
2273
|
+
tip.style.left = pct * 100 + "%";
|
|
2274
|
+
tip.style.opacity = "1";
|
|
2275
|
+
}
|
|
2276
|
+
/** Hide the hover-time tooltip. @private */
|
|
2277
|
+
_hideHoverTip() {
|
|
2278
|
+
if (this.hoverTimeEl) this.hoverTimeEl.style.opacity = "0";
|
|
2279
|
+
}
|
|
2280
|
+
/**
|
|
2281
|
+
* Visually preview a seek during a drag — moves the playhead + handle +
|
|
2282
|
+
* tooltip to the cursor WITHOUT touching the audio (playback continues; the
|
|
2283
|
+
* real seek is committed on release).
|
|
2284
|
+
* @param {number} clientX - Pointer client-X coordinate.
|
|
2285
|
+
* @private
|
|
2286
|
+
*/
|
|
2287
|
+
_scrubTo(clientX) {
|
|
2288
|
+
const rect = this.canvas.getBoundingClientRect();
|
|
2289
|
+
if (!rect.width) return;
|
|
2290
|
+
this.progress = clamp((clientX - rect.left) / rect.width);
|
|
2291
|
+
this.drawWaveform();
|
|
2292
|
+
this._updateSeekHandle();
|
|
2293
|
+
const dur = this.getSeekDuration();
|
|
2294
|
+
if (dur && this.currentTimeEl) {
|
|
2295
|
+
this.currentTimeEl.textContent = formatTime(this.progress * dur);
|
|
2296
|
+
this._hideHoverTip();
|
|
2297
|
+
} else {
|
|
2298
|
+
this._updateHoverTip(clientX);
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
/**
|
|
2302
|
+
* Create the draggable seek handle — a DOM circle over the playhead, shown
|
|
2303
|
+
* only on hover / drag (Spotify-style). Pointer-events are off so it never
|
|
2304
|
+
* blocks the canvas scrub; size + visibility are CSS.
|
|
2305
|
+
* @private
|
|
2306
|
+
*/
|
|
2307
|
+
setupSeekHandle() {
|
|
2308
|
+
if (!this.options.seekHandle || this.options.waveformStyle !== "seekbar" || !this.seekEl) return;
|
|
2309
|
+
const h = document.createElement("div");
|
|
2310
|
+
h.className = "waveform-seek-handle";
|
|
2311
|
+
h.setAttribute("aria-hidden", "true");
|
|
2312
|
+
this.seekEl.appendChild(h);
|
|
2313
|
+
this.seekHandleEl = h;
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* Position the seek handle at the current progress and toggle its
|
|
2317
|
+
* visibility (hover / drag) + expanded (drag / direct-hover) classes.
|
|
2318
|
+
* @private
|
|
2319
|
+
*/
|
|
2320
|
+
_updateSeekHandle() {
|
|
2321
|
+
const h = this.seekHandleEl;
|
|
2322
|
+
if (!h) return;
|
|
2323
|
+
h.style.left = this.progress * 100 + "%";
|
|
2324
|
+
h.classList.toggle("is-visible", this._seekHover || this._dragging);
|
|
2325
|
+
h.classList.toggle("is-active", this._dragging || this._handleNear);
|
|
2326
|
+
}
|
|
2327
|
+
// ============================================
|
|
2328
|
+
// Event Handlers
|
|
2329
|
+
// ============================================
|
|
2330
|
+
/**
|
|
2331
|
+
* Seek to the clicked horizontal position on the waveform canvas.
|
|
2332
|
+
*
|
|
2333
|
+
* Converts the click X into a 0..1 percentage. In external mode it
|
|
2334
|
+
* dispatches a cancelable `waveformplayer:request-seek` event (updating the
|
|
2335
|
+
* local visual optimistically unless the controller vetoes it); in self
|
|
2336
|
+
* mode it seeks the owned `<audio>` via
|
|
2337
|
+
* {@link WaveformPlayer#seekToPercent}.
|
|
2338
|
+
* @param {MouseEvent} event - The canvas click event.
|
|
2339
|
+
* @private
|
|
2340
|
+
* @fires WaveformPlayer#waveformplayer:request-seek
|
|
2341
|
+
*/
|
|
2342
|
+
handleCanvasClick(event) {
|
|
2343
|
+
if (this._suppressClick) {
|
|
2344
|
+
this._suppressClick = false;
|
|
2345
|
+
return;
|
|
2346
|
+
}
|
|
2347
|
+
this._seekFromPointer(event.clientX);
|
|
2348
|
+
}
|
|
2349
|
+
/**
|
|
2350
|
+
* Seek to a horizontal client-X position over the canvas — shared by
|
|
2351
|
+
* click and drag. In external mode the player has no audio of its own,
|
|
2352
|
+
* so it dispatches a cancelable `waveformplayer:request-seek` with the
|
|
2353
|
+
* target percentage (updating the local visual optimistically); in self
|
|
2354
|
+
* mode it seeks the owned `<audio>` via
|
|
2355
|
+
* {@link WaveformPlayer#seekToPercent}.
|
|
2356
|
+
* @param {number} clientX - Pointer client-X coordinate.
|
|
2357
|
+
* @private
|
|
2358
|
+
* @fires WaveformPlayer#waveformplayer:request-seek
|
|
2359
|
+
*/
|
|
2360
|
+
_seekFromPointer(clientX) {
|
|
2361
|
+
const rect = this.canvas.getBoundingClientRect();
|
|
2362
|
+
if (!rect.width) return;
|
|
2363
|
+
const targetPercent = clamp((clientX - rect.left) / rect.width);
|
|
2364
|
+
if (this.options.audioMode === "external") {
|
|
2365
|
+
this._requestSeek(targetPercent);
|
|
2366
|
+
return;
|
|
2367
|
+
}
|
|
2368
|
+
if (!this.audio || !this.audio.duration) return;
|
|
2369
|
+
this.seekToPercent(targetPercent);
|
|
2370
|
+
}
|
|
2371
|
+
/**
|
|
2372
|
+
* Toggle the loading state: show/hide the spinner overlay and set
|
|
2373
|
+
* `aria-busy` on the accessible seek slider so assistive tech knows the
|
|
2374
|
+
* player is fetching/decoding.
|
|
2375
|
+
* @param {boolean} loading - True while audio is loading.
|
|
2376
|
+
* @private
|
|
2377
|
+
*/
|
|
2378
|
+
setLoading(loading) {
|
|
2379
|
+
this.isLoading = loading;
|
|
2380
|
+
if (this.loadingEl) {
|
|
2381
|
+
const showIndicator = loading && this.waveformData.length === 0;
|
|
2382
|
+
this.loadingEl.style.display = showIndicator ? "block" : "none";
|
|
2383
|
+
}
|
|
2384
|
+
if (this.seekEl) {
|
|
2385
|
+
this.seekEl.setAttribute("aria-busy", loading ? "true" : "false");
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
/**
|
|
2389
|
+
* `loadedmetadata` handler (self mode): write the total-time display, now
|
|
2390
|
+
* that duration is known re-render markers, and publish duration to the
|
|
2391
|
+
* accessible seek slider. No-op during destruction.
|
|
2392
|
+
* @private
|
|
2393
|
+
*/
|
|
2394
|
+
onMetadataLoaded() {
|
|
2395
|
+
if (this.isDestroying) return;
|
|
2396
|
+
if (this.totalTimeEl) {
|
|
2397
|
+
this.totalTimeEl.textContent = formatTime(this.audio.duration);
|
|
2398
|
+
}
|
|
2399
|
+
this.renderMarkers();
|
|
2400
|
+
this.updateSeekAccessibility();
|
|
2401
|
+
}
|
|
2402
|
+
/**
|
|
2403
|
+
* Reflect play/pause state on the transport button: toggle the `playing`
|
|
2404
|
+
* class and swap the play/pause icon visibility. The single source of
|
|
2405
|
+
* truth shared by `onPlay`, `onPause`, and the external-mode
|
|
2406
|
+
* `setPlayingState` pump so they can't drift. No-op without a button.
|
|
2407
|
+
* @param {boolean} isPlaying - Whether playback is active.
|
|
2408
|
+
* @private
|
|
2409
|
+
*/
|
|
2410
|
+
setPlayButtonState(isPlaying) {
|
|
2411
|
+
if (!this.playBtn) return;
|
|
2412
|
+
this.playBtn.classList.toggle("playing", isPlaying);
|
|
2413
|
+
const playIcon = this.playBtn.querySelector(".waveform-icon-play");
|
|
2414
|
+
const pauseIcon = this.playBtn.querySelector(".waveform-icon-pause");
|
|
2415
|
+
if (playIcon) playIcon.style.display = isPlaying ? "none" : "flex";
|
|
2416
|
+
if (pauseIcon) pauseIcon.style.display = isPlaying ? "flex" : "none";
|
|
2417
|
+
}
|
|
2418
|
+
/**
|
|
2419
|
+
* `play` handler (self mode): set the playing flag, swap the button to its
|
|
2420
|
+
* pause icon, start the smooth progress loop, dispatch
|
|
2421
|
+
* `waveformplayer:play`, and fire the `onPlay` callback. No-op during
|
|
2422
|
+
* destruction.
|
|
2423
|
+
* @private
|
|
2424
|
+
* @fires WaveformPlayer#waveformplayer:play
|
|
2425
|
+
*/
|
|
2426
|
+
onPlay() {
|
|
2427
|
+
if (this.isDestroying) return;
|
|
2428
|
+
this.isPlaying = true;
|
|
2429
|
+
this.setPlayButtonState(true);
|
|
2430
|
+
this.startSmoothUpdate();
|
|
2431
|
+
this._updateMediaSession("playing");
|
|
2432
|
+
this._emit("waveformplayer:play", { player: this, url: this.options.url });
|
|
2433
|
+
if (this.options.onPlay) {
|
|
2434
|
+
this.options.onPlay(this);
|
|
2435
|
+
}
|
|
2436
|
+
}
|
|
2437
|
+
/**
|
|
2438
|
+
* `pause` handler (self mode): clear the playing flag, swap the button back
|
|
2439
|
+
* to its play icon, stop the smooth progress loop, dispatch
|
|
2440
|
+
* `waveformplayer:pause`, and fire the `onPause` callback. No-op during
|
|
2441
|
+
* destruction.
|
|
2442
|
+
* @private
|
|
2443
|
+
* @fires WaveformPlayer#waveformplayer:pause
|
|
2444
|
+
*/
|
|
2445
|
+
onPause() {
|
|
2446
|
+
if (this.isDestroying) return;
|
|
2447
|
+
this.isPlaying = false;
|
|
2448
|
+
this.setPlayButtonState(false);
|
|
2449
|
+
this.stopSmoothUpdate();
|
|
2450
|
+
this._updateMediaSession("paused");
|
|
2451
|
+
this._emit("waveformplayer:pause", { player: this, url: this.options.url });
|
|
2452
|
+
if (this.options.onPause) {
|
|
2453
|
+
this.options.onPause(this);
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
/**
|
|
2457
|
+
* `ended` handler (self mode): reset progress and `currentTime` to the
|
|
2458
|
+
* 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.
|
|
2461
|
+
* @private
|
|
2462
|
+
* @fires WaveformPlayer#waveformplayer:ended
|
|
2463
|
+
*/
|
|
2464
|
+
onEnded() {
|
|
2465
|
+
if (this.isDestroying) return;
|
|
2466
|
+
const duration = this.audio.duration;
|
|
2467
|
+
this.progress = 0;
|
|
2468
|
+
this.audio.currentTime = 0;
|
|
2469
|
+
this.drawWaveform();
|
|
2470
|
+
if (this.currentTimeEl) {
|
|
2471
|
+
this.currentTimeEl.textContent = "0:00";
|
|
2472
|
+
}
|
|
2473
|
+
this._emit("waveformplayer:ended", { player: this, url: this.options.url, currentTime: duration, duration });
|
|
2474
|
+
this.onPause();
|
|
2475
|
+
if (this.options.onEnd) {
|
|
2476
|
+
this.options.onEnd(this);
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
/**
|
|
2480
|
+
* `error` handler: set the error flag, hide the spinner, reveal the error
|
|
2481
|
+
* overlay, dim the canvas, disable the play button, and fire the `onError`
|
|
2482
|
+
* callback. No-op during destruction.
|
|
2483
|
+
* @param {Event|Error} error - The audio error event, or an Error thrown
|
|
2484
|
+
* during loading.
|
|
2485
|
+
* @private
|
|
2486
|
+
*/
|
|
2487
|
+
onError(error) {
|
|
2488
|
+
if (this.isDestroying) return;
|
|
2489
|
+
console.error("[WaveformPlayer] Audio error:", error);
|
|
2490
|
+
this.hasError = true;
|
|
2491
|
+
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
|
+
if (this.options.onError) {
|
|
2502
|
+
this.options.onError(error, this);
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
// ============================================
|
|
2506
|
+
// Progress Updates
|
|
2507
|
+
// ============================================
|
|
2508
|
+
/**
|
|
2509
|
+
* Start the `requestAnimationFrame` loop that drives smooth progress
|
|
2510
|
+
* updates while playing (self mode only — external mode is redrawn by
|
|
2511
|
+
* controller {@link WaveformPlayer#setProgress} pushes). Cancels any
|
|
2512
|
+
* existing loop first so it's safe to call repeatedly.
|
|
2513
|
+
* @private
|
|
2514
|
+
*/
|
|
2515
|
+
startSmoothUpdate() {
|
|
2516
|
+
this.stopSmoothUpdate();
|
|
2517
|
+
const update = () => {
|
|
2518
|
+
if (this.isPlaying && this.audio && this.audio.duration) {
|
|
2519
|
+
this.updateProgress();
|
|
2520
|
+
this.updateTimer = requestAnimationFrame(update);
|
|
2521
|
+
}
|
|
2522
|
+
};
|
|
2523
|
+
this.updateTimer = requestAnimationFrame(update);
|
|
2524
|
+
}
|
|
2525
|
+
/**
|
|
2526
|
+
* Cancel the smooth-update animation frame, if one is scheduled.
|
|
2527
|
+
* @private
|
|
2528
|
+
*/
|
|
2529
|
+
stopSmoothUpdate() {
|
|
2530
|
+
if (this.updateTimer) {
|
|
2531
|
+
cancelAnimationFrame(this.updateTimer);
|
|
2532
|
+
this.updateTimer = null;
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
/**
|
|
2536
|
+
* Recompute progress from the owned `<audio>` clock and reflect it
|
|
2537
|
+
* everywhere (self mode only — external mode uses
|
|
2538
|
+
* {@link WaveformPlayer#setProgress}).
|
|
2539
|
+
*
|
|
2540
|
+
* Redraws the canvas when progress moves meaningfully, updates the
|
|
2541
|
+
* current-time display, dispatches `waveformplayer:timeupdate`, fires the
|
|
2542
|
+
* `onTimeUpdate` callback, and refreshes the accessible slider values.
|
|
2543
|
+
* @private
|
|
2544
|
+
* @fires WaveformPlayer#waveformplayer:timeupdate
|
|
2545
|
+
*/
|
|
2546
|
+
updateProgress() {
|
|
2547
|
+
if (!this.audio || !this.audio.duration) return;
|
|
2548
|
+
if (this._dragging) return;
|
|
2549
|
+
const newProgress = this.audio.currentTime / this.audio.duration;
|
|
2550
|
+
if (Math.abs(newProgress - this.progress) > 1e-3) {
|
|
2551
|
+
this.progress = newProgress;
|
|
2552
|
+
this.drawWaveform();
|
|
2553
|
+
this._updateSeekHandle();
|
|
2554
|
+
}
|
|
2555
|
+
if (this.currentTimeEl) {
|
|
2556
|
+
this.currentTimeEl.textContent = formatTime(this.audio.currentTime);
|
|
2557
|
+
}
|
|
2558
|
+
this._emit("waveformplayer:timeupdate", {
|
|
2559
|
+
player: this,
|
|
2560
|
+
currentTime: this.audio.currentTime,
|
|
2561
|
+
duration: this.audio.duration,
|
|
2562
|
+
progress: this.progress,
|
|
2563
|
+
url: this.options.url
|
|
2564
|
+
});
|
|
2565
|
+
if (this.options.onTimeUpdate) {
|
|
2566
|
+
this.options.onTimeUpdate(this.audio.currentTime, this.audio.duration, this);
|
|
2567
|
+
}
|
|
2568
|
+
this.updateActiveMarker();
|
|
2569
|
+
this.updateSeekAccessibility();
|
|
2570
|
+
}
|
|
2571
|
+
// ============================================
|
|
2572
|
+
// UI Updates
|
|
2573
|
+
// ============================================
|
|
2574
|
+
/**
|
|
2575
|
+
* Show the detected BPM in the badge, once a value has been detected.
|
|
2576
|
+
* @private
|
|
2577
|
+
*/
|
|
2578
|
+
updateBPMDisplay() {
|
|
2579
|
+
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";
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
/**
|
|
2586
|
+
* Re-detect the page theme and re-apply auto colours + redraw, so an
|
|
2587
|
+
* auto-themed player adapts to a runtime light/dark switch (not just the
|
|
2588
|
+
* value present on load). No-op when the player uses an explicit
|
|
2589
|
+
* `colorPreset` or hand-set colours. Driven by the shared theme watcher.
|
|
2590
|
+
* @public
|
|
2591
|
+
*/
|
|
2592
|
+
refreshTheme() {
|
|
2593
|
+
if (!this._autoTheme) return;
|
|
2594
|
+
this._scheme = detectColorScheme(this.container);
|
|
2595
|
+
const preset = getColorPreset(this.options.colorPreset, this.container);
|
|
2596
|
+
for (const key of this._presetKeys || []) {
|
|
2597
|
+
if (key in preset) this.options[key] = preset[key];
|
|
2598
|
+
}
|
|
2599
|
+
this._applyThemeColors();
|
|
2600
|
+
}
|
|
2601
|
+
/**
|
|
2602
|
+
* Sync the theme class (CSS drives the DOM chrome colours via `--wfp-*`
|
|
2603
|
+
* variables) and redraw the canvas with the resolved waveform colours.
|
|
2604
|
+
* @private
|
|
2605
|
+
*/
|
|
2606
|
+
_applyThemeColors() {
|
|
2607
|
+
this.container.classList.toggle("waveform-theme-light", this._scheme === "light");
|
|
2608
|
+
if (this.canvas) this.drawWaveform();
|
|
2609
|
+
}
|
|
2610
|
+
/**
|
|
2611
|
+
* Lazily install ONE shared watcher that re-detects the theme for every
|
|
2612
|
+
* auto-themed instance when the document theme changes — a class/attribute
|
|
2613
|
+
* flip on `<html>`/`<body>` (Tailwind `dark`, `data-theme`,
|
|
2614
|
+
* `data-color-scheme`) or an OS `prefers-color-scheme` change. Event-driven
|
|
2615
|
+
* (MutationObserver + matchMedia), never a timer.
|
|
2616
|
+
* @private
|
|
2617
|
+
*/
|
|
2618
|
+
static _watchTheme() {
|
|
2619
|
+
if (_WaveformPlayer._themeWatch || typeof document === "undefined") return;
|
|
2620
|
+
const refresh = () => requestAnimationFrame(() => {
|
|
2621
|
+
_WaveformPlayer.instances.forEach((p) => {
|
|
2622
|
+
try {
|
|
2623
|
+
p.refreshTheme();
|
|
2624
|
+
} catch (e) {
|
|
2625
|
+
}
|
|
2626
|
+
});
|
|
2627
|
+
});
|
|
2628
|
+
const opts = { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme", "style"] };
|
|
2629
|
+
const obs = new MutationObserver(refresh);
|
|
2630
|
+
obs.observe(document.documentElement, opts);
|
|
2631
|
+
if (document.body) obs.observe(document.body, opts);
|
|
2632
|
+
let mq = null;
|
|
2633
|
+
try {
|
|
2634
|
+
mq = window.matchMedia("(prefers-color-scheme: dark)");
|
|
2635
|
+
mq.addEventListener("change", refresh);
|
|
2636
|
+
} catch (e) {
|
|
2637
|
+
}
|
|
2638
|
+
_WaveformPlayer._themeWatch = { obs, mq, refresh };
|
|
2639
|
+
}
|
|
2640
|
+
/**
|
|
2641
|
+
* Sync the speed control's label and the menu's active-option highlight to
|
|
2642
|
+
* the audio element's current `playbackRate`. No-op in external mode (no
|
|
2643
|
+
* owned `<audio>`), which also avoids reading `playbackRate` before the
|
|
2644
|
+
* element exists.
|
|
2645
|
+
* @private
|
|
2646
|
+
*/
|
|
2647
|
+
updateSpeedUI() {
|
|
2648
|
+
if (!this.audio) return;
|
|
2649
|
+
const speedValue = this.container.querySelector(".speed-value");
|
|
2650
|
+
if (speedValue) {
|
|
2651
|
+
const rate = this.audio.playbackRate;
|
|
2652
|
+
speedValue.textContent = rate === 1 ? "1x" : `${rate}x`;
|
|
2653
|
+
}
|
|
2654
|
+
this.container.querySelectorAll(".speed-option").forEach((btn) => {
|
|
2655
|
+
const on = parseFloat(btn.dataset.rate) === this.audio.playbackRate;
|
|
2656
|
+
btn.classList.toggle("active", on);
|
|
2657
|
+
btn.setAttribute("aria-checked", on ? "true" : "false");
|
|
2658
|
+
});
|
|
2659
|
+
}
|
|
2660
|
+
// ============================================
|
|
2661
|
+
// Public API
|
|
2662
|
+
// ============================================
|
|
2663
|
+
/**
|
|
2664
|
+
* Play audio.
|
|
2665
|
+
*
|
|
2666
|
+
* In `audioMode: 'self'` (default): calls the underlying <audio>
|
|
2667
|
+
* element's play(). Returns the promise from HTMLMediaElement.play().
|
|
2668
|
+
*
|
|
2669
|
+
* In `audioMode: 'external'`: dispatches a cancelable
|
|
2670
|
+
* `waveformplayer:request-play` event with the track metadata and
|
|
2671
|
+
* does NOT touch any audio element. Returns `undefined`. An external
|
|
2672
|
+
* controller (e.g. WaveformBar) listens for this event and starts
|
|
2673
|
+
* playback on its own audio source, then pushes state back via
|
|
2674
|
+
* setPlayingState() / setProgress(). Calling preventDefault() on
|
|
2675
|
+
* the event lets the controller veto the play (state is unchanged).
|
|
2676
|
+
*
|
|
2677
|
+
* When `singlePlay` is enabled, any other currently-playing instance is
|
|
2678
|
+
* paused first.
|
|
2679
|
+
*
|
|
2680
|
+
* @return {Promise|undefined} The promise from `HTMLMediaElement.play()` in
|
|
2681
|
+
* self mode; `undefined` in external mode.
|
|
2682
|
+
* @fires WaveformPlayer#waveformplayer:request-play
|
|
2683
|
+
*/
|
|
2684
|
+
play() {
|
|
2685
|
+
if (this.options.singlePlay && _WaveformPlayer.currentlyPlaying && _WaveformPlayer.currentlyPlaying !== this) {
|
|
2686
|
+
_WaveformPlayer.currentlyPlaying.pause();
|
|
2687
|
+
}
|
|
2688
|
+
if (this.options.audioMode === "external") {
|
|
2689
|
+
const evt = this._emit("waveformplayer:request-play", this._buildTrackDetail(), true);
|
|
2690
|
+
if (!evt.defaultPrevented) {
|
|
2691
|
+
_WaveformPlayer.currentlyPlaying = this;
|
|
2692
|
+
}
|
|
2693
|
+
return void 0;
|
|
2694
|
+
}
|
|
2695
|
+
_WaveformPlayer.currentlyPlaying = this;
|
|
2696
|
+
return this.audio.play();
|
|
2697
|
+
}
|
|
2698
|
+
/**
|
|
2699
|
+
* Pause audio.
|
|
2700
|
+
*
|
|
2701
|
+
* In `audioMode: 'external'`, dispatches `waveformplayer:request-pause`
|
|
2702
|
+
* (cancelable) and does NOT touch any audio element. See play().
|
|
2703
|
+
*
|
|
2704
|
+
* @fires WaveformPlayer#waveformplayer:request-pause
|
|
2705
|
+
*/
|
|
2706
|
+
pause() {
|
|
2707
|
+
if (_WaveformPlayer.currentlyPlaying === this) {
|
|
2708
|
+
_WaveformPlayer.currentlyPlaying = null;
|
|
2709
|
+
}
|
|
2710
|
+
if (this.options.audioMode === "external") {
|
|
2711
|
+
this._emit("waveformplayer:request-pause", this._buildTrackDetail(), true);
|
|
2712
|
+
return;
|
|
2713
|
+
}
|
|
2714
|
+
this.audio.pause();
|
|
2715
|
+
}
|
|
2716
|
+
/**
|
|
2717
|
+
* Build the track detail object dispatched by request-play /
|
|
2718
|
+
* request-pause events in external audio mode. Mirrors the shape
|
|
2719
|
+
* WaveformBar.play() accepts so a controller can forward it
|
|
2720
|
+
* directly: `WaveformBar.play(event.detail)`.
|
|
2721
|
+
*
|
|
2722
|
+
* @private
|
|
2723
|
+
* @return {{url:string,title:?string,artist:?string,artwork:?string,player:WaveformPlayer}}
|
|
2724
|
+
*/
|
|
2725
|
+
_buildTrackDetail() {
|
|
2726
|
+
return {
|
|
2727
|
+
url: this.options.url,
|
|
2728
|
+
title: this.options.title,
|
|
2729
|
+
artist: this.options.artist,
|
|
2730
|
+
artwork: this.options.artwork,
|
|
2731
|
+
markers: this.options.markers,
|
|
2732
|
+
waveform: this.options.waveform,
|
|
2733
|
+
id: this.id,
|
|
2734
|
+
player: this
|
|
2735
|
+
};
|
|
2736
|
+
}
|
|
2737
|
+
/**
|
|
2738
|
+
* External-mode state pump: flip the play/pause visual state without
|
|
2739
|
+
* touching audio. Mirrors what onPlay()/onPause() do but skips the
|
|
2740
|
+
* audio-element interactions. Safe to call repeatedly — idempotent.
|
|
2741
|
+
*
|
|
2742
|
+
* Only dispatches `waveformplayer:play`/`waveformplayer:pause` (and runs
|
|
2743
|
+
* the matching callback) on an actual transition, starting/stopping the
|
|
2744
|
+
* smooth-update loop accordingly.
|
|
2745
|
+
*
|
|
2746
|
+
* @param {boolean} playing - True to enter the playing state, false to
|
|
2747
|
+
* enter the paused state.
|
|
2748
|
+
* @fires WaveformPlayer#waveformplayer:play
|
|
2749
|
+
* @fires WaveformPlayer#waveformplayer:pause
|
|
2750
|
+
*/
|
|
2751
|
+
setPlayingState(playing) {
|
|
2752
|
+
const wasPlaying = this.isPlaying;
|
|
2753
|
+
this.isPlaying = !!playing;
|
|
2754
|
+
this.setPlayButtonState(this.isPlaying);
|
|
2755
|
+
if (this.isPlaying && !wasPlaying) {
|
|
2756
|
+
this.startSmoothUpdate?.();
|
|
2757
|
+
this._emit("waveformplayer:play", { player: this, url: this.options.url });
|
|
2758
|
+
if (this.options.onPlay) this.options.onPlay(this);
|
|
2759
|
+
} else if (!this.isPlaying && wasPlaying) {
|
|
2760
|
+
this.stopSmoothUpdate?.();
|
|
2761
|
+
this._emit("waveformplayer:pause", { player: this, url: this.options.url });
|
|
2762
|
+
if (this.options.onPause) this.options.onPause(this);
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
/**
|
|
2766
|
+
* External-mode state pump: update the visualization's progress
|
|
2767
|
+
* from an external clock (e.g. WaveformBar's audio element's
|
|
2768
|
+
* timeupdate). Drives the canvas redraw + the time displays.
|
|
2769
|
+
*
|
|
2770
|
+
* Redraws the canvas, updates the current/total time displays, stores the
|
|
2771
|
+
* external duration for the accessible slider, dispatches
|
|
2772
|
+
* `waveformplayer:timeupdate`, runs `onTimeUpdate`, and synthesizes a
|
|
2773
|
+
* one-shot `waveformplayer:ended` (with `onEnd`) when progress reaches the
|
|
2774
|
+
* end. No-op for a non-positive duration.
|
|
2775
|
+
*
|
|
2776
|
+
* @param {number} currentTime - Current playback position in seconds.
|
|
2777
|
+
* @param {number} duration - Total track duration in seconds.
|
|
2778
|
+
* @fires WaveformPlayer#waveformplayer:timeupdate
|
|
2779
|
+
* @fires WaveformPlayer#waveformplayer:ended
|
|
2780
|
+
*/
|
|
2781
|
+
setProgress(currentTime, duration) {
|
|
2782
|
+
if (!duration || duration <= 0) return;
|
|
2783
|
+
this.progress = clamp(currentTime / duration);
|
|
2784
|
+
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);
|
|
2790
|
+
}
|
|
2791
|
+
this.drawWaveform?.();
|
|
2792
|
+
this.updateActiveMarker();
|
|
2793
|
+
this._emit("waveformplayer:timeupdate", { player: this, currentTime, duration, progress: this.progress, url: this.options.url });
|
|
2794
|
+
if (this.options.onTimeUpdate) this.options.onTimeUpdate(currentTime, duration, this);
|
|
2795
|
+
if (this.progress >= 1) {
|
|
2796
|
+
if (!this._extEnded) {
|
|
2797
|
+
this._extEnded = true;
|
|
2798
|
+
this._emit("waveformplayer:ended", { player: this, url: this.options.url, currentTime: duration, duration });
|
|
2799
|
+
if (this.options.onEnd) this.options.onEnd(this);
|
|
2800
|
+
}
|
|
2801
|
+
} else {
|
|
2802
|
+
this._extEnded = false;
|
|
2803
|
+
}
|
|
2804
|
+
this.updateSeekAccessibility();
|
|
2805
|
+
}
|
|
2806
|
+
/**
|
|
2807
|
+
* Toggle between play and pause based on the current `isPlaying` state.
|
|
2808
|
+
* Works in both audio modes (in external mode it routes through the
|
|
2809
|
+
* request-play/pause events).
|
|
2810
|
+
*/
|
|
2811
|
+
togglePlay() {
|
|
2812
|
+
if (this.isPlaying) {
|
|
2813
|
+
this.pause();
|
|
2814
|
+
} else {
|
|
2815
|
+
this.play();
|
|
2816
|
+
}
|
|
2817
|
+
}
|
|
2818
|
+
/**
|
|
2819
|
+
* Seek the owned `<audio>` element to an absolute time, clamped to
|
|
2820
|
+
* `[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.
|
|
2823
|
+
* @param {number} seconds - Target time in seconds.
|
|
2824
|
+
*/
|
|
2825
|
+
seekTo(seconds) {
|
|
2826
|
+
if (this.audio && this.audio.duration) {
|
|
2827
|
+
this.audio.currentTime = clamp(seconds, 0, this.audio.duration);
|
|
2828
|
+
this.updateProgress();
|
|
2829
|
+
}
|
|
2830
|
+
}
|
|
2831
|
+
/**
|
|
2832
|
+
* Seek the owned `<audio>` element to a fraction of the track, clamped to
|
|
2833
|
+
* `[0, 1]`, and refresh progress. Self mode only — a no-op without an audio
|
|
2834
|
+
* element or duration.
|
|
2835
|
+
* @param {number} percent - Position as a fraction from 0 to 1.
|
|
2836
|
+
*/
|
|
2837
|
+
seekToPercent(percent) {
|
|
2838
|
+
if (this.audio && this.audio.duration) {
|
|
2839
|
+
this.audio.currentTime = this.audio.duration * clamp(percent);
|
|
2840
|
+
this.updateProgress();
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2843
|
+
/**
|
|
2844
|
+
* Set the owned `<audio>` element's volume, clamped to `[0, 1]`. Self mode
|
|
2845
|
+
* only — a no-op in external mode where the controller owns volume.
|
|
2846
|
+
* @param {number} volume - Volume from 0 (silent) to 1 (full).
|
|
2847
|
+
*/
|
|
2848
|
+
setVolume(volume) {
|
|
2849
|
+
const v = Number(volume);
|
|
2850
|
+
if (this.audio && Number.isFinite(v)) {
|
|
2851
|
+
this.audio.volume = clamp(v);
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2854
|
+
/**
|
|
2855
|
+
* Set the owned `<audio>` element's playback rate (clamped to 0.25–4),
|
|
2856
|
+
* persist it onto `this.options.playbackRate`, and refresh the speed UI.
|
|
2857
|
+
* Self mode only — a no-op in external mode.
|
|
2858
|
+
*
|
|
2859
|
+
* The clamp bounds the range browsers keep audible; the default speed menu
|
|
2860
|
+
* offers a narrower 0.5–2, which `playbackRates` can widen up to these
|
|
2861
|
+
* bounds. A non-numeric rate is ignored rather than assigned, since
|
|
2862
|
+
* `audio.playbackRate = NaN` throws.
|
|
2863
|
+
* @param {number} rate - Desired playback rate; clamped to the 0.25–4 range.
|
|
2864
|
+
*/
|
|
2865
|
+
setPlaybackRate(rate) {
|
|
2866
|
+
if (!this.audio) return;
|
|
2867
|
+
const clampedRate = toFiniteNumber(rate, null, { min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX });
|
|
2868
|
+
if (clampedRate === null) return;
|
|
2869
|
+
this.audio.playbackRate = clampedRate;
|
|
2870
|
+
this.options.playbackRate = clampedRate;
|
|
2871
|
+
this.updateSpeedUI();
|
|
2872
|
+
}
|
|
2873
|
+
/**
|
|
2874
|
+
* Tear down the player and release all resources.
|
|
2875
|
+
*
|
|
2876
|
+
* Flags destruction (so in-flight handlers bail), dispatches
|
|
2877
|
+
* `waveformplayer:destroy`, stops playback and the animation loop, aborts
|
|
2878
|
+
* every listener registered on the instance signal, disconnects the resize
|
|
2879
|
+
* observer, removes the window-resize handler, drops the instance from the
|
|
2880
|
+
* static map and `currentlyPlaying`, resets/releases the audio element, and
|
|
2881
|
+
* empties the container.
|
|
2882
|
+
* @fires WaveformPlayer#waveformplayer:destroy
|
|
2883
|
+
*/
|
|
2884
|
+
destroy() {
|
|
2885
|
+
this.isDestroying = true;
|
|
2886
|
+
this._emit("waveformplayer:destroy", { player: this, url: this.options.url });
|
|
2887
|
+
this.pause();
|
|
2888
|
+
this.stopSmoothUpdate();
|
|
2889
|
+
clearTimeout(this._markerLabelTimer);
|
|
2890
|
+
this._ac?.abort();
|
|
2891
|
+
if (this.resizeObserver) {
|
|
2892
|
+
this.resizeObserver.disconnect();
|
|
2893
|
+
this.resizeObserver = null;
|
|
2894
|
+
}
|
|
2895
|
+
if (this.resizeHandler) {
|
|
2896
|
+
window.removeEventListener("resize", this.resizeHandler);
|
|
2897
|
+
this.resizeHandler = null;
|
|
2898
|
+
}
|
|
2899
|
+
_WaveformPlayer.instances.delete(this.id);
|
|
2900
|
+
if (_WaveformPlayer.currentlyPlaying === this) {
|
|
2901
|
+
_WaveformPlayer.currentlyPlaying = null;
|
|
2902
|
+
}
|
|
2903
|
+
if (this.audio) {
|
|
2904
|
+
this.audio.pause();
|
|
2905
|
+
this.audio.src = "";
|
|
2906
|
+
this.audio.load();
|
|
2907
|
+
this.audio = null;
|
|
2908
|
+
}
|
|
2909
|
+
this.container.innerHTML = "";
|
|
2910
|
+
delete this.container.dataset.waveformInitialized;
|
|
2911
|
+
this.canvas = null;
|
|
2912
|
+
this.ctx = null;
|
|
2913
|
+
this.playBtn = null;
|
|
2914
|
+
this.waveformData = [];
|
|
2915
|
+
}
|
|
2916
|
+
// ============================================
|
|
2917
|
+
// Static Methods
|
|
2918
|
+
// ============================================
|
|
2919
|
+
/**
|
|
2920
|
+
* Get player instance by ID, element, or element ID
|
|
2921
|
+
* @param {string|HTMLElement} idOrElement - Player ID, element, or element ID
|
|
2922
|
+
* @returns {WaveformPlayer|undefined}
|
|
2923
|
+
*/
|
|
2924
|
+
static getInstance(idOrElement) {
|
|
2925
|
+
if (typeof idOrElement === "string") {
|
|
2926
|
+
const instance = this.instances.get(idOrElement);
|
|
2927
|
+
if (instance) return instance;
|
|
2928
|
+
const element = document.getElementById(idOrElement);
|
|
2929
|
+
if (element) {
|
|
2930
|
+
return Array.from(this.instances.values()).find((p) => p.container === element);
|
|
2931
|
+
}
|
|
2932
|
+
}
|
|
2933
|
+
if (idOrElement instanceof HTMLElement) {
|
|
2934
|
+
return Array.from(this.instances.values()).find((p) => p.container === idOrElement);
|
|
2935
|
+
}
|
|
2936
|
+
return void 0;
|
|
2937
|
+
}
|
|
2938
|
+
/**
|
|
2939
|
+
* Get all player instances
|
|
2940
|
+
* @returns {WaveformPlayer[]}
|
|
2941
|
+
*/
|
|
2942
|
+
static getAllInstances() {
|
|
2943
|
+
return Array.from(this.instances.values());
|
|
2944
|
+
}
|
|
2945
|
+
/**
|
|
2946
|
+
* Destroy all player instances
|
|
2947
|
+
*/
|
|
2948
|
+
static destroyAll() {
|
|
2949
|
+
this.instances.forEach((player) => player.destroy());
|
|
2950
|
+
this.instances.clear();
|
|
2951
|
+
}
|
|
2952
|
+
/**
|
|
2953
|
+
* Generate waveform data from audio URL
|
|
2954
|
+
* @static
|
|
2955
|
+
* @param {string} url - Audio URL
|
|
2956
|
+
* @param {number} samples - Number of samples
|
|
2957
|
+
* @returns {Promise<number[]>} Waveform peak data
|
|
2958
|
+
*/
|
|
2959
|
+
static async generateWaveformData(url, samples = DEFAULT_SAMPLES) {
|
|
2960
|
+
try {
|
|
2961
|
+
const result = await generateWaveform(url, samples);
|
|
2962
|
+
return result.peaks;
|
|
2963
|
+
} catch (error) {
|
|
2964
|
+
console.error("[WaveformPlayer] Failed to generate waveform:", error);
|
|
2965
|
+
throw error;
|
|
2966
|
+
}
|
|
2967
|
+
}
|
|
2968
|
+
/**
|
|
2969
|
+
* Derive a peaks-JSON URL from an audio URL by swapping the
|
|
2970
|
+
* extension. Strict counterpart to `generateWaveformData()`:
|
|
2971
|
+
* `generateWaveformData` decodes the audio at runtime,
|
|
2972
|
+
* `getPeaksUrl` assumes you generated the peaks at build time
|
|
2973
|
+
* (e.g. with `@arraypress/waveform-gen`) and stored the JSON
|
|
2974
|
+
* alongside the audio file.
|
|
2975
|
+
*
|
|
2976
|
+
* Use the result as the `waveform` option — the player detects
|
|
2977
|
+
* the `.json` suffix, `fetch()`es the file, and skips the Web
|
|
2978
|
+
* Audio decode pass entirely. Big perf win on catalogues with
|
|
2979
|
+
* many tracks (saves ~1-5s decode per file on slow connections).
|
|
2980
|
+
*
|
|
2981
|
+
* Recognised extensions: mp3, wav, ogg, flac, m4a, aac.
|
|
2982
|
+
* Preserves query strings + URL fragments. Returns `undefined`
|
|
2983
|
+
* for unrecognised inputs so callers can pass through
|
|
2984
|
+
* unconditionally:
|
|
2985
|
+
*
|
|
2986
|
+
* new WaveformPlayer('#el', {
|
|
2987
|
+
* url: track.audioUrl,
|
|
2988
|
+
* waveform: WaveformPlayer.getPeaksUrl(track.audioUrl),
|
|
2989
|
+
* });
|
|
2990
|
+
*
|
|
2991
|
+
* @static
|
|
2992
|
+
* @param {string|undefined|null} audioUrl - Audio file URL.
|
|
2993
|
+
* @returns {string|undefined} Peaks JSON URL, or `undefined`
|
|
2994
|
+
* when the input is empty / has no recognised audio extension.
|
|
2995
|
+
*
|
|
2996
|
+
* @example
|
|
2997
|
+
* WaveformPlayer.getPeaksUrl('/audio/track.mp3')
|
|
2998
|
+
* // '/audio/track.json'
|
|
2999
|
+
*
|
|
3000
|
+
* WaveformPlayer.getPeaksUrl('/audio/track.wav?v=2')
|
|
3001
|
+
* // '/audio/track.json?v=2'
|
|
3002
|
+
*
|
|
3003
|
+
* WaveformPlayer.getPeaksUrl(undefined)
|
|
3004
|
+
* // undefined
|
|
3005
|
+
*/
|
|
3006
|
+
static getPeaksUrl(audioUrl) {
|
|
3007
|
+
if (!audioUrl) return void 0;
|
|
3008
|
+
const swapped = audioUrl.replace(
|
|
3009
|
+
/\.(mp3|wav|ogg|flac|m4a|aac)(\?[^#]*)?(#.*)?$/i,
|
|
3010
|
+
".json$2$3"
|
|
3011
|
+
);
|
|
3012
|
+
return swapped === audioUrl ? void 0 : swapped;
|
|
3013
|
+
}
|
|
3014
|
+
};
|
|
3015
|
+
|
|
3016
|
+
// src/js/entry.js
|
|
3017
|
+
WaveformPlayer.utils = { formatTime, extractTitleFromUrl, escapeHtml, isSafeHref, parseDataAttributes, detectColorScheme };
|
|
3018
|
+
function initElement(element) {
|
|
3019
|
+
if (element.dataset.waveformInitialized === "true" || WaveformPlayer.getInstance(element)) {
|
|
3020
|
+
return;
|
|
3021
|
+
}
|
|
3022
|
+
try {
|
|
3023
|
+
new WaveformPlayer(element);
|
|
3024
|
+
element.dataset.waveformInitialized = "true";
|
|
3025
|
+
} catch (error) {
|
|
3026
|
+
console.error("[WaveformPlayer] Failed to initialize:", error, element);
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
function autoInit(root = document) {
|
|
3030
|
+
if (!isBrowser()) return;
|
|
3031
|
+
const scope = root || document;
|
|
3032
|
+
if (scope.matches?.("[data-waveform-player]")) {
|
|
3033
|
+
initElement(scope);
|
|
3034
|
+
}
|
|
3035
|
+
scope.querySelectorAll("[data-waveform-player]").forEach(initElement);
|
|
3036
|
+
}
|
|
3037
|
+
WaveformPlayer.init = autoInit;
|
|
3038
|
+
if (isBrowser()) {
|
|
3039
|
+
window.WaveformPlayer = WaveformPlayer;
|
|
3040
|
+
}
|
|
3041
|
+
var entry_default = WaveformPlayer;
|