@arraypress/waveform-player 1.27.1 → 1.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/waveform-player-no-autoinit.cjs +220 -115
- package/dist/waveform-player-no-autoinit.esm.js +5 -5
- package/dist/waveform-player.cjs +220 -115
- package/dist/waveform-player.css +1 -1
- package/dist/waveform-player.esm.js +5 -5
- package/dist/waveform-player.js +220 -115
- package/dist/waveform-player.min.js +5 -5
- package/index.d.ts +43 -12
- package/package.json +1 -1
- package/src/css/waveform-player.css +3 -1
- package/src/js/bpm.js +11 -5
- package/src/js/core.js +286 -124
- package/src/js/drawing.js +19 -4
- package/src/js/themes.js +3 -1
- package/src/js/utils.js +6 -4
package/src/js/core.js
CHANGED
|
@@ -153,6 +153,10 @@ export class WaveformPlayer {
|
|
|
153
153
|
this.hasError = false;
|
|
154
154
|
this.updateTimer = null;
|
|
155
155
|
this.resizeObserver = null;
|
|
156
|
+
// Load ticket: every load() takes the next one, and anything that
|
|
157
|
+
// resumes after an await checks it still holds the current one before
|
|
158
|
+
// touching state. See load().
|
|
159
|
+
this._loadId = 0;
|
|
156
160
|
|
|
157
161
|
// All DOM/document listeners are registered with this signal so a
|
|
158
162
|
// single abort() in destroy() tears every one of them down (the old
|
|
@@ -185,8 +189,10 @@ export class WaveformPlayer {
|
|
|
185
189
|
throw error;
|
|
186
190
|
}
|
|
187
191
|
|
|
188
|
-
// Dispatch ready event after initialization
|
|
189
|
-
|
|
192
|
+
// Dispatch ready event after initialization. Kept so destroy() can
|
|
193
|
+
// cancel it — a player torn down inside this window must not announce
|
|
194
|
+
// itself to listeners that already saw its destroy event.
|
|
195
|
+
this._readyTimer = setTimeout(() => {
|
|
190
196
|
this._emit('waveformplayer:ready', {player: this, url: this.options.url});
|
|
191
197
|
}, 100);
|
|
192
198
|
}
|
|
@@ -247,10 +253,15 @@ export class WaveformPlayer {
|
|
|
247
253
|
|
|
248
254
|
// Ensure proper sizing after DOM is ready
|
|
249
255
|
requestAnimationFrame(() => {
|
|
256
|
+
// Destroyed before the first frame (a wrapper that mounts and
|
|
257
|
+
// unmounts in one tick): don't start a load for a dead player.
|
|
258
|
+
if (this.isDestroying) return;
|
|
250
259
|
this.resizeCanvas();
|
|
251
260
|
|
|
252
|
-
// Load audio if URL provided
|
|
253
|
-
|
|
261
|
+
// Load audio if URL provided — unless the caller already started
|
|
262
|
+
// a load()/loadTrack() before this frame, which would otherwise
|
|
263
|
+
// be decoded twice and superseded by this one.
|
|
264
|
+
if (this.options.url && !this._loadId) {
|
|
254
265
|
this.load(this.options.url).then(() => {
|
|
255
266
|
if (this.options.autoplay) {
|
|
256
267
|
this.play()?.catch(() => {});
|
|
@@ -630,8 +641,11 @@ export class WaveformPlayer {
|
|
|
630
641
|
// WaveformBar) owns playback rate. Skip the audio init but
|
|
631
642
|
// still bind the speed control UI in case the controller
|
|
632
643
|
// wants to mirror rate changes via events later.
|
|
644
|
+
// defaultPlaybackRate too: the media load algorithm resets
|
|
645
|
+
// playbackRate to it on every src change, so setting playbackRate
|
|
646
|
+
// alone is silently undone by the first load().
|
|
633
647
|
if (this.audio && this.options.playbackRate && this.options.playbackRate !== 1) {
|
|
634
|
-
this.audio.playbackRate = this.options.playbackRate;
|
|
648
|
+
this.audio.playbackRate = this.audio.defaultPlaybackRate = this.options.playbackRate;
|
|
635
649
|
}
|
|
636
650
|
|
|
637
651
|
// Initialize speed control UI if enabled
|
|
@@ -969,6 +983,10 @@ export class WaveformPlayer {
|
|
|
969
983
|
// Session handlers; ours would conflict with its.
|
|
970
984
|
if (!this.audio) return;
|
|
971
985
|
|
|
986
|
+
// The session is one global object; remember whose it is, so a
|
|
987
|
+
// paused player's seek can't move another player's lock-screen
|
|
988
|
+
// scrubber (see _updatePositionState).
|
|
989
|
+
WaveformPlayer._sessionOwner = this;
|
|
972
990
|
this._applyMediaMetadata();
|
|
973
991
|
|
|
974
992
|
// Set up action handlers
|
|
@@ -1026,14 +1044,26 @@ export class WaveformPlayer {
|
|
|
1026
1044
|
// drive the player you're actually listening to, not the last one loaded.
|
|
1027
1045
|
if (state === 'playing') this.initMediaSession();
|
|
1028
1046
|
navigator.mediaSession.playbackState = state;
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1047
|
+
this._updatePositionState();
|
|
1048
|
+
} catch (e) { /* Media Session is best-effort */ }
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
/**
|
|
1052
|
+
* Publish duration, rate and position to the lock-screen scrubber. Runs
|
|
1053
|
+
* on play/pause and on the element's `seeked` / `ratechange`, so the
|
|
1054
|
+
* scrubber doesn't drift after a seek or a speed change until the next
|
|
1055
|
+
* play/pause. Only the player that owns the (global) session writes it.
|
|
1056
|
+
* @private
|
|
1057
|
+
*/
|
|
1058
|
+
_updatePositionState() {
|
|
1059
|
+
const d = this.audio?.duration;
|
|
1060
|
+
if (WaveformPlayer._sessionOwner !== this || !navigator.mediaSession?.setPositionState || !(d && isFinite(d))) return;
|
|
1061
|
+
try {
|
|
1062
|
+
navigator.mediaSession.setPositionState({
|
|
1063
|
+
duration: d,
|
|
1064
|
+
playbackRate: this.audio.playbackRate || 1,
|
|
1065
|
+
position: clamp(this.audio.currentTime, 0, d),
|
|
1066
|
+
});
|
|
1037
1067
|
} catch (e) { /* Media Session is best-effort */ }
|
|
1038
1068
|
}
|
|
1039
1069
|
|
|
@@ -1068,6 +1098,18 @@ export class WaveformPlayer {
|
|
|
1068
1098
|
this.audio.addEventListener('pause', () => this.onPause());
|
|
1069
1099
|
this.audio.addEventListener('ended', () => this.onEnded());
|
|
1070
1100
|
this.audio.addEventListener('error', (e) => this.onError(e));
|
|
1101
|
+
// Progress is normally driven by the rAF loop (smooth canvas), but
|
|
1102
|
+
// browsers stop animation frames in background tabs while the
|
|
1103
|
+
// audio keeps playing — and with them every timeupdate event and
|
|
1104
|
+
// onTimeUpdate call, which is what analytics (waveform-tracker)
|
|
1105
|
+
// count listening time from. The native event (~4Hz, still fired
|
|
1106
|
+
// in the background) takes over only once the loop has gone quiet,
|
|
1107
|
+
// so a foreground tab doesn't emit twice.
|
|
1108
|
+
this.audio.addEventListener('seeked', () => this._updatePositionState());
|
|
1109
|
+
this.audio.addEventListener('ratechange', () => this._updatePositionState());
|
|
1110
|
+
this.audio.addEventListener('timeupdate', () => {
|
|
1111
|
+
if (this.isPlaying && Date.now() - this._frameAt > 500) this.updateProgress();
|
|
1112
|
+
});
|
|
1071
1113
|
}
|
|
1072
1114
|
|
|
1073
1115
|
// Canvas interactions — click + drag to seek. pointerdown starts a
|
|
@@ -1179,19 +1221,39 @@ export class WaveformPlayer {
|
|
|
1179
1221
|
* accessible name are written *before* the metadata wait, as are peaks
|
|
1180
1222
|
* supplied via the `waveform` option — none of them need anything from the
|
|
1181
1223
|
* audio element, and behind the wait they blink in on a slow origin.
|
|
1182
|
-
* Without inline peaks
|
|
1183
|
-
*
|
|
1184
|
-
* on success.
|
|
1224
|
+
* Without inline peaks — or when a `.json` peaks sidecar can't be fetched —
|
|
1225
|
+
* the waveform is decoded from the audio instead; a decode failure falls
|
|
1226
|
+
* back to a placeholder. The `onLoad` callback fires on success.
|
|
1227
|
+
*
|
|
1228
|
+
* Every call supersedes the previous one: a load that is overtaken while
|
|
1229
|
+
* it awaits (metadata, a sidecar fetch, the decode) stops there without
|
|
1230
|
+
* touching the player, so a slow first track can't land its peaks, BPM,
|
|
1231
|
+
* error or loading state on the track that replaced it.
|
|
1232
|
+
*
|
|
1233
|
+
* Loading a *different* URL also resets what the previous track left
|
|
1234
|
+
* behind (see {@link WaveformPlayer#_resetTrack}); reloading the same URL
|
|
1235
|
+
* — e.g. a retry after an error — keeps the drawn waveform. Either way the
|
|
1236
|
+
* error state is cleared, so a retry re-enables the player.
|
|
1185
1237
|
* @param {string} url - Audio URL.
|
|
1186
1238
|
* @returns {Promise<void>} Resolves once loading settles (errors are caught
|
|
1187
1239
|
* internally and surfaced through {@link WaveformPlayer#onError}).
|
|
1188
1240
|
*/
|
|
1189
1241
|
async load(url) {
|
|
1242
|
+
const id = ++this._loadId;
|
|
1243
|
+
// Held locally: destroy() nulls this.audio while the metadata wait
|
|
1244
|
+
// below is still pending, and its handlers must still be able to
|
|
1245
|
+
// unhook themselves and settle the promise.
|
|
1246
|
+
const audio = this.audio;
|
|
1190
1247
|
try {
|
|
1248
|
+
if (url !== this.options.url) this._resetTrack();
|
|
1191
1249
|
this.setLoading(true);
|
|
1192
1250
|
this.progress = 0;
|
|
1193
|
-
this.
|
|
1251
|
+
this._setError(false);
|
|
1194
1252
|
this.container.classList.remove('waveform-is-placeholder');
|
|
1253
|
+
// A detected tempo describes the audio that was decoded, not the
|
|
1254
|
+
// one being loaded. A caller's `bpm` option still shows at once.
|
|
1255
|
+
this.detectedBPM = null;
|
|
1256
|
+
this.updateBPMDisplay();
|
|
1195
1257
|
|
|
1196
1258
|
// Record the URL first so every event emitted from here on (and
|
|
1197
1259
|
// the extensions that read options.url, e.g. waveform-tracker)
|
|
@@ -1203,11 +1265,10 @@ export class WaveformPlayer {
|
|
|
1203
1265
|
// playback state, so draw them up front rather than behind the
|
|
1204
1266
|
// metadata wait below. On a slow (or non-Range-capable) audio
|
|
1205
1267
|
// origin that wait is seconds long, and the canvas used to sit
|
|
1206
|
-
// blank for all of it. See issue #23.
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
}
|
|
1268
|
+
// blank for all of it. See issue #23. A `.json` sidecar comes back
|
|
1269
|
+
// as a promise, fetched in parallel with the metadata wait.
|
|
1270
|
+
const inlinePeaks = this.options.waveform;
|
|
1271
|
+
const sidecar = inlinePeaks ? this.setWaveformData(inlinePeaks) : null;
|
|
1211
1272
|
|
|
1212
1273
|
// Same reasoning as the peaks above: the title comes from the
|
|
1213
1274
|
// `title` option or the URL, so it needs nothing from the audio
|
|
@@ -1226,9 +1287,9 @@ export class WaveformPlayer {
|
|
|
1226
1287
|
// waveform peaks so the canvas can render the visualization.
|
|
1227
1288
|
// Duration / current time come from the external controller
|
|
1228
1289
|
// via setProgress().
|
|
1229
|
-
if (
|
|
1290
|
+
if (audio) {
|
|
1230
1291
|
// Set audio source
|
|
1231
|
-
|
|
1292
|
+
audio.src = url;
|
|
1232
1293
|
|
|
1233
1294
|
// preload="none" tells the browser to fetch nothing until
|
|
1234
1295
|
// play(), so `loadedmetadata` will never arrive and awaiting
|
|
@@ -1237,30 +1298,32 @@ export class WaveformPlayer {
|
|
|
1237
1298
|
// wait; the bindEvents() `loadedmetadata` listener still
|
|
1238
1299
|
// fires whenever metadata does land, and onMetadataLoaded()
|
|
1239
1300
|
// fills in duration + markers then.
|
|
1240
|
-
if (
|
|
1301
|
+
if (audio.preload !== 'none') {
|
|
1241
1302
|
// Wait for metadata to load
|
|
1242
1303
|
await new Promise((resolve, reject) => {
|
|
1243
|
-
const
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1304
|
+
const settle = (fn) => (e) => {
|
|
1305
|
+
audio.removeEventListener('loadedmetadata', metadataHandler);
|
|
1306
|
+
audio.removeEventListener('error', errorHandler);
|
|
1307
|
+
fn(e);
|
|
1247
1308
|
};
|
|
1248
|
-
const
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
};
|
|
1253
|
-
this.audio.addEventListener('loadedmetadata', metadataHandler);
|
|
1254
|
-
this.audio.addEventListener('error', errorHandler);
|
|
1309
|
+
const metadataHandler = settle(resolve);
|
|
1310
|
+
const errorHandler = settle(reject);
|
|
1311
|
+
audio.addEventListener('loadedmetadata', metadataHandler);
|
|
1312
|
+
audio.addEventListener('error', errorHandler);
|
|
1255
1313
|
});
|
|
1256
1314
|
}
|
|
1257
1315
|
}
|
|
1258
1316
|
|
|
1259
|
-
//
|
|
1260
|
-
|
|
1261
|
-
|
|
1317
|
+
// `false` = the sidecar couldn't be used; `undefined` = inline
|
|
1318
|
+
// peaks (already drawn) or none at all.
|
|
1319
|
+
const sidecarOk = await sidecar;
|
|
1320
|
+
if (id !== this._loadId) return;
|
|
1321
|
+
|
|
1322
|
+
// No usable caller-supplied peaks: decode them from the audio.
|
|
1323
|
+
if (!inlinePeaks || sidecarOk === false) {
|
|
1262
1324
|
try {
|
|
1263
1325
|
const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
|
|
1326
|
+
if (id !== this._loadId) return;
|
|
1264
1327
|
this.waveformData = result.peaks;
|
|
1265
1328
|
|
|
1266
1329
|
// Store BPM if detected
|
|
@@ -1269,6 +1332,7 @@ export class WaveformPlayer {
|
|
|
1269
1332
|
this.updateBPMDisplay();
|
|
1270
1333
|
}
|
|
1271
1334
|
} catch (error) {
|
|
1335
|
+
if (id !== this._loadId) return;
|
|
1272
1336
|
console.warn('[WaveformPlayer] Using placeholder waveform:', error);
|
|
1273
1337
|
this.waveformData = generatePlaceholderWaveform(this.options.samples);
|
|
1274
1338
|
this.container.classList.add('waveform-is-placeholder');
|
|
@@ -1284,12 +1348,52 @@ export class WaveformPlayer {
|
|
|
1284
1348
|
}
|
|
1285
1349
|
} catch (error) {
|
|
1286
1350
|
// onError() is the single funnel for surfacing + logging errors.
|
|
1287
|
-
|
|
1351
|
+
// A self-mode media error reaches it twice — the bindEvents()
|
|
1352
|
+
// `error` listener runs first, then this rejection — so one
|
|
1353
|
+
// failure must not report twice. A superseded load's failure
|
|
1354
|
+
// belongs to a track nobody is waiting for.
|
|
1355
|
+
if (id === this._loadId && !this.hasError) this.onError(error);
|
|
1288
1356
|
} finally {
|
|
1289
|
-
|
|
1357
|
+
// Only the current load owns the loading state; a superseded one
|
|
1358
|
+
// finishing must not clear it while its successor is still busy.
|
|
1359
|
+
if (id === this._loadId) this.setLoading(false);
|
|
1290
1360
|
}
|
|
1291
1361
|
}
|
|
1292
1362
|
|
|
1363
|
+
/**
|
|
1364
|
+
* Forget everything the previous track left on the player: its peaks,
|
|
1365
|
+
* progress, duration (external mode), time readout and marker buttons.
|
|
1366
|
+
* Shared by {@link WaveformPlayer#loadTrack} and a {@link WaveformPlayer#load}
|
|
1367
|
+
* of a different URL, so neither path can show the old track's `1:30` or
|
|
1368
|
+
* place the new track's markers against the old duration. Per-track
|
|
1369
|
+
* *options* are reset by `loadTrack()`, which is the path that receives them.
|
|
1370
|
+
* @private
|
|
1371
|
+
*/
|
|
1372
|
+
_resetTrack() {
|
|
1373
|
+
this.progress = 0;
|
|
1374
|
+
this.waveformData = [];
|
|
1375
|
+
this._extDuration = 0;
|
|
1376
|
+
this._extEnded = false;
|
|
1377
|
+
if (this.currentTimeEl) this.currentTimeEl.textContent = '0:00';
|
|
1378
|
+
if (this.totalTimeEl) this.totalTimeEl.textContent = '0:00';
|
|
1379
|
+
if (this.markersContainer) this.markersContainer.innerHTML = '';
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
/**
|
|
1383
|
+
* Show or clear the error state: the overlay, the dimmed canvas and the
|
|
1384
|
+
* disabled play button. The one place both {@link WaveformPlayer#onError}
|
|
1385
|
+
* and a fresh {@link WaveformPlayer#load} flip it, so a retry can't leave
|
|
1386
|
+
* half of it behind.
|
|
1387
|
+
* @param {boolean} on - True to enter the error state, false to clear it.
|
|
1388
|
+
* @private
|
|
1389
|
+
*/
|
|
1390
|
+
_setError(on) {
|
|
1391
|
+
this.hasError = on;
|
|
1392
|
+
if (this.errorEl) this.errorEl.style.display = on ? 'flex' : 'none';
|
|
1393
|
+
if (this.canvas) this.canvas.style.opacity = on ? '0.2' : '1';
|
|
1394
|
+
if (this.playBtn) this.playBtn.disabled = on;
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1293
1397
|
/**
|
|
1294
1398
|
* Swap the player to a new track at runtime.
|
|
1295
1399
|
*
|
|
@@ -1297,14 +1401,22 @@ export class WaveformPlayer {
|
|
|
1297
1401
|
* clears error/marker/progress state, merges the new metadata into
|
|
1298
1402
|
* `this.options`, updates the artist/artwork DOM, then calls
|
|
1299
1403
|
* {@link WaveformPlayer#load}. Auto-plays the new track unless
|
|
1300
|
-
* `options.autoplay === false
|
|
1404
|
+
* `options.autoplay === false` — and only if no later `loadTrack()` /
|
|
1405
|
+
* `load()` has superseded this one by the time it finishes loading.
|
|
1406
|
+
*
|
|
1407
|
+
* Per-track options the caller doesn't repeat are reset rather than
|
|
1408
|
+
* inherited from the previous track: `markers`, `waveform`, `bpm` and
|
|
1409
|
+
* `album`.
|
|
1301
1410
|
* @param {string} url - Audio URL.
|
|
1302
1411
|
* @param {string|null} [title=null] - Track title; keeps the existing
|
|
1303
|
-
* title when null.
|
|
1412
|
+
* title when null. (Deliberate: a controller that only swaps the
|
|
1413
|
+
* audio keeps the label it set. Pass `''` to derive the title from the
|
|
1414
|
+
* URL instead.)
|
|
1304
1415
|
* @param {string|null} [artist=null] - Track artist; pass `''` to hide
|
|
1305
1416
|
* the artist row, or null to keep the existing one.
|
|
1306
1417
|
* @param {Object} [options={}] - Additional options to merge (e.g.
|
|
1307
|
-
* `preload`, `artwork`, `artworkAlt`, `markers`, `
|
|
1418
|
+
* `preload`, `artwork`, `artworkAlt`, `markers`, `bpm`, `album`,
|
|
1419
|
+
* `autoplay`).
|
|
1308
1420
|
* @returns {Promise<void>}
|
|
1309
1421
|
*/
|
|
1310
1422
|
async loadTrack(url, title = null, artist = null, options = {}) {
|
|
@@ -1322,21 +1434,9 @@ export class WaveformPlayer {
|
|
|
1322
1434
|
this.audio.load();
|
|
1323
1435
|
}
|
|
1324
1436
|
|
|
1325
|
-
//
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
this.errorEl.style.display = 'none';
|
|
1329
|
-
}
|
|
1330
|
-
if (this.canvas) {
|
|
1331
|
-
this.canvas.style.opacity = '1';
|
|
1332
|
-
}
|
|
1333
|
-
if (this.playBtn) {
|
|
1334
|
-
this.playBtn.disabled = false;
|
|
1335
|
-
}
|
|
1336
|
-
|
|
1337
|
-
// Reset state
|
|
1338
|
-
this.progress = 0;
|
|
1339
|
-
this.waveformData = [];
|
|
1437
|
+
// Peaks, progress, duration, time readout, markers. The error state
|
|
1438
|
+
// is cleared by load() itself, so a plain load() retry gets it too.
|
|
1439
|
+
this._resetTrack();
|
|
1340
1440
|
|
|
1341
1441
|
// Update options (including preload if specified). Normalized on the
|
|
1342
1442
|
// same terms as the constructor — loadTrack takes a fresh, caller-
|
|
@@ -1356,6 +1456,13 @@ export class WaveformPlayer {
|
|
|
1356
1456
|
this.options.artworkAlt = this.options.artwork ? DEFAULT_OPTIONS.artworkAlt : '';
|
|
1357
1457
|
}
|
|
1358
1458
|
|
|
1459
|
+
// `bpm` and `album` describe one track. mergeOptions() skips null
|
|
1460
|
+
// sources, so without this the previous track's tempo badge and
|
|
1461
|
+
// lock-screen album would carry over to every track after it.
|
|
1462
|
+
for (const key of ['bpm', 'album']) {
|
|
1463
|
+
if (options[key] == null) this.options[key] = DEFAULT_OPTIONS[key];
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1359
1466
|
// Apply preload setting if it was changed. The caller's value decides
|
|
1360
1467
|
// WHETHER to apply; the normalized one decides WHAT to apply, so an
|
|
1361
1468
|
// unsupported value can't reach the media element.
|
|
@@ -1394,12 +1501,17 @@ export class WaveformPlayer {
|
|
|
1394
1501
|
// waveform (audio changes, visualization doesn't).
|
|
1395
1502
|
this.options.waveform = options.waveform || null;
|
|
1396
1503
|
|
|
1397
|
-
// Load the new track
|
|
1398
|
-
|
|
1504
|
+
// Load the new track. load() takes its ticket synchronously, so this
|
|
1505
|
+
// is the id to compare against once it settles.
|
|
1506
|
+
const loading = this.load(url);
|
|
1507
|
+
const id = this._loadId;
|
|
1508
|
+
await loading;
|
|
1399
1509
|
|
|
1400
1510
|
// Auto-play the new track unless the caller opted out — lets a
|
|
1401
|
-
// controller load/restore/enqueue without forcing playback.
|
|
1402
|
-
|
|
1511
|
+
// controller load/restore/enqueue without forcing playback. A track
|
|
1512
|
+
// that was superseded while loading must not start (or, in external
|
|
1513
|
+
// mode, request) playback over the one that replaced it.
|
|
1514
|
+
if (options.autoplay !== false && id === this._loadId) {
|
|
1403
1515
|
this.play()?.catch(() => {});
|
|
1404
1516
|
}
|
|
1405
1517
|
}
|
|
@@ -1412,31 +1524,58 @@ export class WaveformPlayer {
|
|
|
1412
1524
|
* Normalise externally-supplied waveform data into `this.waveformData` and
|
|
1413
1525
|
* redraw.
|
|
1414
1526
|
*
|
|
1415
|
-
* Accepts several shapes: a `.json` URL (fetched async
|
|
1416
|
-
*
|
|
1417
|
-
* a
|
|
1418
|
-
*
|
|
1527
|
+
* Accepts several shapes: a `.json` URL (fetched async — a query string
|
|
1528
|
+
* or fragment is fine, which is what {@link WaveformPlayer.getPeaksUrl}
|
|
1529
|
+
* produces for a versioned audio URL), a JSON-encoded array string, a
|
|
1530
|
+
* comma-separated number string, or a plain number array. Malformed input
|
|
1531
|
+
* degrades to an empty array rather than throwing.
|
|
1532
|
+
*
|
|
1533
|
+
* A sidecar may be a bare peaks array or a `{peaks, markers, bpm}` object
|
|
1534
|
+
* (the shape `@arraypress/waveform-gen` writes): its markers apply when the
|
|
1535
|
+
* track has none of its own, and its `bpm` feeds the badge when no `bpm`
|
|
1536
|
+
* option is set. A sidecar that fails to fetch (network error, non-2xx) or
|
|
1537
|
+
* carries no peaks resolves `false` and leaves the canvas as it was —
|
|
1538
|
+
* {@link WaveformPlayer#load} then decodes the audio instead. One that
|
|
1539
|
+
* resolves after a newer load has started is discarded.
|
|
1419
1540
|
* @param {string|number[]} data - Peaks as an array, a JSON/CSV string, or
|
|
1420
1541
|
* a URL to a `.json` peaks file.
|
|
1421
|
-
* @
|
|
1542
|
+
* @returns {Promise<boolean>|undefined} For a `.json` URL, a promise of
|
|
1543
|
+
* whether the sidecar was applied; otherwise `undefined` (applied
|
|
1544
|
+
* synchronously).
|
|
1422
1545
|
*/
|
|
1423
1546
|
setWaveformData(data) {
|
|
1424
|
-
// URL to JSON file — fetch peaks and maybe markers
|
|
1425
|
-
if (typeof data === 'string' &&
|
|
1426
|
-
|
|
1427
|
-
|
|
1547
|
+
// URL to JSON file — fetch peaks and maybe markers / bpm
|
|
1548
|
+
if (typeof data === 'string' && /\.json(?:[?#]|$)/i.test(data.trim())) {
|
|
1549
|
+
const id = this._loadId;
|
|
1550
|
+
return fetch(data.trim())
|
|
1551
|
+
.then(r => {
|
|
1552
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
1553
|
+
return r.json();
|
|
1554
|
+
})
|
|
1428
1555
|
.then(json => {
|
|
1429
|
-
|
|
1556
|
+
if (id !== this._loadId) return false;
|
|
1557
|
+
const peaks = toNumberArray(Array.isArray(json) ? json : json?.peaks, {fallback: []});
|
|
1558
|
+
if (!peaks.length) throw new Error('no peaks');
|
|
1559
|
+
this.waveformData = peaks;
|
|
1430
1560
|
// A peaks sidecar is a third source of markers, and a remote
|
|
1431
1561
|
// one — normalize it on the same terms as the option paths.
|
|
1432
1562
|
if (json.markers && !this.options.markers?.length) {
|
|
1433
1563
|
this.options.markers = normalizeMarkers(json.markers);
|
|
1434
1564
|
this.renderMarkers();
|
|
1435
1565
|
}
|
|
1566
|
+
// A `bpm` option still wins — updateBPMDisplay() prefers it.
|
|
1567
|
+
const bpm = toFiniteNumber(json.bpm, null, {min: 1});
|
|
1568
|
+
if (bpm) {
|
|
1569
|
+
this.detectedBPM = bpm;
|
|
1570
|
+
this.updateBPMDisplay();
|
|
1571
|
+
}
|
|
1436
1572
|
this.drawWaveform();
|
|
1573
|
+
return true;
|
|
1437
1574
|
})
|
|
1438
|
-
.catch(
|
|
1439
|
-
|
|
1575
|
+
.catch(error => {
|
|
1576
|
+
console.warn('[WaveformPlayer] Could not use peaks file:', data, error);
|
|
1577
|
+
return false;
|
|
1578
|
+
});
|
|
1440
1579
|
}
|
|
1441
1580
|
|
|
1442
1581
|
// Peaks may arrive as an array, a JSON array string, or a bare
|
|
@@ -1468,8 +1607,9 @@ export class WaveformPlayer {
|
|
|
1468
1607
|
/**
|
|
1469
1608
|
* Re-fit the canvas backing store to its parent's width and the configured
|
|
1470
1609
|
* height, scaled by the device pixel ratio for crisp rendering, then
|
|
1471
|
-
* redraw. Guards against running after destruction.
|
|
1472
|
-
*
|
|
1610
|
+
* redraw. Guards against running after destruction. Public: the resize
|
|
1611
|
+
* observer doesn't reliably fire on a DOM move, so call this after
|
|
1612
|
+
* relocating the player.
|
|
1473
1613
|
*/
|
|
1474
1614
|
resizeCanvas() {
|
|
1475
1615
|
// Guard against calls after destruction
|
|
@@ -1888,8 +2028,8 @@ export class WaveformPlayer {
|
|
|
1888
2028
|
/**
|
|
1889
2029
|
* `ended` handler (self mode): reset progress and `currentTime` to the
|
|
1890
2030
|
* start, redraw, reset the time display, dispatch `waveformplayer:ended`
|
|
1891
|
-
* (carrying the final time), run {@link WaveformPlayer#onPause}
|
|
1892
|
-
* the `onEnd` callback. No-op during destruction.
|
|
2031
|
+
* (carrying the final time), run {@link WaveformPlayer#onPause} if the
|
|
2032
|
+
* preceding `pause` event hasn't already, and fire the `onEnd` callback. No-op during destruction.
|
|
1893
2033
|
* @private
|
|
1894
2034
|
* @fires WaveformPlayer#waveformplayer:ended
|
|
1895
2035
|
*/
|
|
@@ -1912,7 +2052,10 @@ export class WaveformPlayer {
|
|
|
1912
2052
|
// analytics) don't have to reach into player.audio.
|
|
1913
2053
|
this._emit('waveformplayer:ended', {player: this, url: this.options.url, currentTime: duration, duration});
|
|
1914
2054
|
|
|
1915
|
-
|
|
2055
|
+
// Browsers fire `pause` before `ended` at the end of a track, and
|
|
2056
|
+
// onPause() has usually run already — only settle into paused here
|
|
2057
|
+
// if it hasn't, or listeners see two pause events for one stop.
|
|
2058
|
+
if (this.isPlaying) this.onPause();
|
|
1916
2059
|
|
|
1917
2060
|
if (this.options.onEnd) {
|
|
1918
2061
|
this.options.onEnd(this);
|
|
@@ -1932,21 +2075,9 @@ export class WaveformPlayer {
|
|
|
1932
2075
|
if (this.isDestroying) return;
|
|
1933
2076
|
|
|
1934
2077
|
console.error('[WaveformPlayer] Audio error:', error);
|
|
1935
|
-
this.
|
|
2078
|
+
this._setError(true);
|
|
1936
2079
|
this.setLoading(false);
|
|
1937
2080
|
|
|
1938
|
-
if (this.errorEl) {
|
|
1939
|
-
this.errorEl.style.display = 'flex';
|
|
1940
|
-
}
|
|
1941
|
-
|
|
1942
|
-
if (this.canvas) {
|
|
1943
|
-
this.canvas.style.opacity = '0.2';
|
|
1944
|
-
}
|
|
1945
|
-
|
|
1946
|
-
if (this.playBtn) {
|
|
1947
|
-
this.playBtn.disabled = true;
|
|
1948
|
-
}
|
|
1949
|
-
|
|
1950
2081
|
if (this.options.onError) {
|
|
1951
2082
|
this.options.onError(error, this);
|
|
1952
2083
|
}
|
|
@@ -1971,11 +2102,15 @@ export class WaveformPlayer {
|
|
|
1971
2102
|
// setProgress() pushes from the controller — no internal
|
|
1972
2103
|
// RAF needed. Self-mode keeps the smooth-update loop.
|
|
1973
2104
|
if (this.isPlaying && this.audio && this.audio.duration) {
|
|
2105
|
+
this._frameAt = Date.now();
|
|
1974
2106
|
this.updateProgress();
|
|
1975
2107
|
this.updateTimer = requestAnimationFrame(update);
|
|
1976
2108
|
}
|
|
1977
2109
|
};
|
|
1978
2110
|
|
|
2111
|
+
// Arm the stall clock too: the native `timeupdate` fallback (see
|
|
2112
|
+
// bindEvents) must not fire before the first frame has had a chance.
|
|
2113
|
+
this._frameAt = Date.now();
|
|
1979
2114
|
this.updateTimer = requestAnimationFrame(update);
|
|
1980
2115
|
}
|
|
1981
2116
|
|
|
@@ -2043,7 +2178,9 @@ export class WaveformPlayer {
|
|
|
2043
2178
|
// ============================================
|
|
2044
2179
|
|
|
2045
2180
|
/**
|
|
2046
|
-
* Show the
|
|
2181
|
+
* Show the track's BPM in the badge, or hide the badge when the current
|
|
2182
|
+
* track has none — a load resets the detected value, so the previous
|
|
2183
|
+
* track's tempo can't linger on the next one.
|
|
2047
2184
|
* @private
|
|
2048
2185
|
*/
|
|
2049
2186
|
updateBPMDisplay() {
|
|
@@ -2051,9 +2188,9 @@ export class WaveformPlayer {
|
|
|
2051
2188
|
// are pre-generated (so the audio is never decoded) but the BPM is known
|
|
2052
2189
|
// anyway, e.g. sample-pack previews where the tempo is in the metadata.
|
|
2053
2190
|
const bpm = this.options.bpm || this.detectedBPM;
|
|
2054
|
-
if (this.bpmEl && this.bpmValueEl
|
|
2055
|
-
this.bpmValueEl.textContent = Math.round(bpm);
|
|
2056
|
-
this.bpmEl.style.display = 'inline-flex';
|
|
2191
|
+
if (this.bpmEl && this.bpmValueEl) {
|
|
2192
|
+
if (bpm) this.bpmValueEl.textContent = Math.round(bpm);
|
|
2193
|
+
this.bpmEl.style.display = bpm ? 'inline-flex' : 'none';
|
|
2057
2194
|
}
|
|
2058
2195
|
}
|
|
2059
2196
|
|
|
@@ -2185,20 +2322,22 @@ export class WaveformPlayer {
|
|
|
2185
2322
|
/**
|
|
2186
2323
|
* Pause audio.
|
|
2187
2324
|
*
|
|
2188
|
-
* In `audioMode: 'external'`, dispatches
|
|
2189
|
-
*
|
|
2325
|
+
* In `audioMode: 'external'`, dispatches a cancelable
|
|
2326
|
+
* `waveformplayer:request-pause` and does NOT touch any audio element.
|
|
2327
|
+
* Mirrors play(): calling preventDefault() on the event vetoes the pause
|
|
2328
|
+
* as far as the player is concerned — it stays `currentlyPlaying` (the
|
|
2329
|
+
* `singlePlay` bookkeeping). Neither event flips the play/pause visual;
|
|
2330
|
+
* that only changes when the controller calls setPlayingState().
|
|
2190
2331
|
*
|
|
2191
2332
|
* @fires WaveformPlayer#waveformplayer:request-pause
|
|
2192
2333
|
*/
|
|
2193
2334
|
pause() {
|
|
2194
|
-
|
|
2335
|
+
const accepted = this.options.audioMode !== 'external' ||
|
|
2336
|
+
!this._emit('waveformplayer:request-pause', this._buildTrackDetail(), true).defaultPrevented;
|
|
2337
|
+
if (accepted && WaveformPlayer.currentlyPlaying === this) {
|
|
2195
2338
|
WaveformPlayer.currentlyPlaying = null;
|
|
2196
2339
|
}
|
|
2197
|
-
|
|
2198
|
-
this._emit('waveformplayer:request-pause', this._buildTrackDetail(), true);
|
|
2199
|
-
return;
|
|
2200
|
-
}
|
|
2201
|
-
this.audio.pause();
|
|
2340
|
+
this.audio?.pause();
|
|
2202
2341
|
}
|
|
2203
2342
|
|
|
2204
2343
|
/**
|
|
@@ -2261,7 +2400,8 @@ export class WaveformPlayer {
|
|
|
2261
2400
|
* external duration for the accessible slider, dispatches
|
|
2262
2401
|
* `waveformplayer:timeupdate`, runs `onTimeUpdate`, and synthesizes a
|
|
2263
2402
|
* one-shot `waveformplayer:ended` (with `onEnd`) when progress reaches the
|
|
2264
|
-
* end. No-op for a non-positive duration
|
|
2403
|
+
* end. No-op for a non-positive duration, and while the user is dragging
|
|
2404
|
+
* the playhead (as in self mode).
|
|
2265
2405
|
*
|
|
2266
2406
|
* @param {number} currentTime - Current playback position in seconds.
|
|
2267
2407
|
* @param {number} duration - Total track duration in seconds.
|
|
@@ -2270,18 +2410,24 @@ export class WaveformPlayer {
|
|
|
2270
2410
|
*/
|
|
2271
2411
|
setProgress(currentTime, duration) {
|
|
2272
2412
|
if (!duration || duration <= 0) return;
|
|
2413
|
+
// While the user drags, the playhead previews the cursor and the seek
|
|
2414
|
+
// commits on release — the controller's clock mustn't drag it back
|
|
2415
|
+
// (self mode's updateProgress() bails the same way).
|
|
2416
|
+
if (this._dragging) return;
|
|
2273
2417
|
this.progress = clamp(currentTime / duration);
|
|
2274
2418
|
// Mirror the existing display update code so callers don't have
|
|
2275
2419
|
// to know which DOM elements live where.
|
|
2276
2420
|
if (this.currentTimeEl) this.currentTimeEl.textContent = formatTime(currentTime);
|
|
2277
2421
|
// Publish the duration unconditionally — the accessible seek slider
|
|
2278
2422
|
// and keyboard seeking read getSeekDuration()/_extDuration even when
|
|
2279
|
-
// there's no time display to update.
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
this.
|
|
2423
|
+
// there's no time display to update. A new duration (first push, or
|
|
2424
|
+
// a new track — loadTrack() zeroes it) is also what markers were
|
|
2425
|
+
// waiting for: load() ran before any duration existed, so this is
|
|
2426
|
+
// the first point they can be placed.
|
|
2427
|
+
if (duration !== this._extDuration) {
|
|
2428
|
+
this._extDuration = duration;
|
|
2429
|
+
if (this.totalTimeEl) this.totalTimeEl.textContent = formatTime(duration);
|
|
2430
|
+
this.renderMarkers();
|
|
2285
2431
|
}
|
|
2286
2432
|
this.drawWaveform?.();
|
|
2287
2433
|
this.updateActiveMarker();
|
|
@@ -2322,13 +2468,16 @@ export class WaveformPlayer {
|
|
|
2322
2468
|
/**
|
|
2323
2469
|
* Seek the owned `<audio>` element to an absolute time, clamped to
|
|
2324
2470
|
* `[0, duration]`, and refresh progress. Self mode only — a no-op when
|
|
2325
|
-
* there is no audio element or duration
|
|
2326
|
-
* seeks go through
|
|
2471
|
+
* there is no audio element or duration, or when `seconds` isn't a finite
|
|
2472
|
+
* number. External-mode keyboard/click seeks go through
|
|
2473
|
+
* {@link WaveformPlayer#seekToSeconds} instead.
|
|
2327
2474
|
* @param {number} seconds - Target time in seconds.
|
|
2328
2475
|
*/
|
|
2329
2476
|
seekTo(seconds) {
|
|
2330
|
-
|
|
2331
|
-
|
|
2477
|
+
// Coerce + guard like setVolume(): `audio.currentTime = NaN` throws.
|
|
2478
|
+
const s = Number(seconds);
|
|
2479
|
+
if (this.audio && this.audio.duration && Number.isFinite(s)) {
|
|
2480
|
+
this.audio.currentTime = clamp(s, 0, this.audio.duration);
|
|
2332
2481
|
this.updateProgress();
|
|
2333
2482
|
}
|
|
2334
2483
|
}
|
|
@@ -2336,12 +2485,13 @@ export class WaveformPlayer {
|
|
|
2336
2485
|
/**
|
|
2337
2486
|
* Seek the owned `<audio>` element to a fraction of the track, clamped to
|
|
2338
2487
|
* `[0, 1]`, and refresh progress. Self mode only — a no-op without an audio
|
|
2339
|
-
* element or duration.
|
|
2488
|
+
* element or duration, or when `percent` isn't a finite number.
|
|
2340
2489
|
* @param {number} percent - Position as a fraction from 0 to 1.
|
|
2341
2490
|
*/
|
|
2342
2491
|
seekToPercent(percent) {
|
|
2343
|
-
|
|
2344
|
-
|
|
2492
|
+
const p = Number(percent);
|
|
2493
|
+
if (this.audio && this.audio.duration && Number.isFinite(p)) {
|
|
2494
|
+
this.audio.currentTime = this.audio.duration * clamp(p);
|
|
2345
2495
|
this.updateProgress();
|
|
2346
2496
|
}
|
|
2347
2497
|
}
|
|
@@ -2368,7 +2518,8 @@ export class WaveformPlayer {
|
|
|
2368
2518
|
* The clamp bounds the range browsers keep audible; the default speed menu
|
|
2369
2519
|
* offers a narrower 0.5–2, which `playbackRates` can widen up to these
|
|
2370
2520
|
* bounds. A non-numeric rate is ignored rather than assigned, since
|
|
2371
|
-
* `audio.playbackRate = NaN` throws.
|
|
2521
|
+
* `audio.playbackRate = NaN` throws. The rate is also written to
|
|
2522
|
+
* `defaultPlaybackRate`, so it survives the next track load.
|
|
2372
2523
|
* @param {number} rate - Desired playback rate; clamped to the 0.25–4 range.
|
|
2373
2524
|
*/
|
|
2374
2525
|
setPlaybackRate(rate) {
|
|
@@ -2376,7 +2527,9 @@ export class WaveformPlayer {
|
|
|
2376
2527
|
|
|
2377
2528
|
const clampedRate = toFiniteNumber(rate, null, {min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX});
|
|
2378
2529
|
if (clampedRate === null) return;
|
|
2379
|
-
|
|
2530
|
+
// The default as well, or the next src change (loadTrack) quietly
|
|
2531
|
+
// drops the listener back to 1x — see initPlaybackSpeed().
|
|
2532
|
+
this.audio.playbackRate = this.audio.defaultPlaybackRate = clampedRate;
|
|
2380
2533
|
this.options.playbackRate = clampedRate;
|
|
2381
2534
|
|
|
2382
2535
|
this.updateSpeedUI();
|
|
@@ -2401,10 +2554,16 @@ export class WaveformPlayer {
|
|
|
2401
2554
|
// before teardown — the symmetric counterpart to waveformplayer:ready.
|
|
2402
2555
|
this._emit('waveformplayer:destroy', {player: this, url: this.options.url});
|
|
2403
2556
|
|
|
2404
|
-
// Stop playback and animations
|
|
2405
|
-
this.pause()
|
|
2557
|
+
// Stop playback and animations. The <audio> itself is paused and
|
|
2558
|
+
// released below; this.pause() isn't called because in external
|
|
2559
|
+
// mode it emits request-pause, and a wrapper remounting an inline
|
|
2560
|
+
// player would pause the controller's (e.g. the bar's) playback.
|
|
2406
2561
|
this.stopSmoothUpdate();
|
|
2407
2562
|
clearTimeout(this._markerLabelTimer);
|
|
2563
|
+
clearTimeout(this._readyTimer);
|
|
2564
|
+
// Supersede any in-flight load() so it stops at its next await
|
|
2565
|
+
// instead of decoding, drawing and firing onLoad for a dead player.
|
|
2566
|
+
this._loadId++;
|
|
2408
2567
|
|
|
2409
2568
|
// Tear down every document/container/seek listener in one shot.
|
|
2410
2569
|
this._ac?.abort();
|
|
@@ -2424,10 +2583,13 @@ export class WaveformPlayer {
|
|
|
2424
2583
|
// Remove from instances map
|
|
2425
2584
|
WaveformPlayer.instances.delete(this.id);
|
|
2426
2585
|
|
|
2427
|
-
// Clear current playing
|
|
2586
|
+
// Clear current playing / Media Session references to this instance
|
|
2428
2587
|
if (WaveformPlayer.currentlyPlaying === this) {
|
|
2429
2588
|
WaveformPlayer.currentlyPlaying = null;
|
|
2430
2589
|
}
|
|
2590
|
+
if (WaveformPlayer._sessionOwner === this) {
|
|
2591
|
+
WaveformPlayer._sessionOwner = null;
|
|
2592
|
+
}
|
|
2431
2593
|
|
|
2432
2594
|
// Properly clean up audio element
|
|
2433
2595
|
if (this.audio) {
|