feat(web): gapless audio handoff to fix desktop media-tile flicker
Add a second <audio> element; S.audio always points at the active one and listeners are bound to both once (handlers guard with el !== S.audio). preloadNext buffers the next track into the standby element, and playCurrent hands playback over to it on skip instead of swapping the source — so the active element never empties and Windows keeps the media tile (also makes forward skips instant/gapless). Safety: handoff only when the standby is buffered (readyState >= 2); falls back to the unchanged source-swap path otherwise, if there's no second element, or if handoff play() rejects. Web-only — the native bridge path is untouched. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
687650518e
commit
98d7c84269
4 files changed
+92
-48
No files matched your search
+1
-1
@@ -74,7 +74,7 @@ Versioning: two-part `MAJOR.MINOR` — each release bumps the minor (features an
|
||||
- **Android** — Offline detail screen flashed open then immediately returned: its initial empty state (before Room emitted) was mistaken for "deleted". Now shows a brief spinner until loaded, and only leaves when the last song is actually removed
|
||||
- **Android** — Lyrics autoscroll: rewrote centering to use the active line's *measured* position in a `LazyColumn` instead of a fixed line-height estimate. Eliminates the stutter and the downward drift on wrapped (multi-line) lyrics — the active line now tracks smoothly and sits at a natural ~40 %-from-top reading anchor
|
||||
- **Web** — Home now refreshes on an explicit Home click (matching Android): the album rows re-fetch and the random row re-randomizes instead of serving the 5-minute cache. Back/forward navigation still keeps the cached state
|
||||
- **Web (PWA)** — OS media tile no longer disappears/reappears when skipping tracks on desktop: the Media Session metadata is now mutated in place instead of replaced with a new `MediaMetadata` each track (which made Windows rebuild the tile)
|
||||
- **Web (PWA)** — OS media tile no longer disappears/reappears when skipping tracks on desktop. Two fixes: (1) the Media Session metadata is mutated in place instead of replaced with a new `MediaMetadata` each track, and (2) gapless handoff — playback is handed to a second, pre-buffered `<audio>` element on skip so the active element never empties (the source-swap gap is what made Windows hide the tile). Falls back to the classic source swap when the next track isn't preloaded
|
||||
|
||||
### Internal
|
||||
- **Android** — Offline system: `Room` DB (`novasonic_offline.db`) with `downloaded_tracks`, `download_groups`, `group_track_cross_refs`; `OfflineRepository` holds hot `StateFlow` maps for O(1) local-path lookups; `DownloadWorker` streams audio + cover art via `HttpURLConnection` to `context.filesDir/offline/{audio|covers}/`. `MusicRepository.streamUrl()` checks local files first, so playback uses the `file://` URI on every entry point
|
||||
|
||||
@@ -742,6 +742,7 @@
|
||||
|
||||
<div class="toast-container" id="toast-container"></div>
|
||||
<audio id="audio-element" preload="auto" playsinline crossorigin="anonymous"></audio>
|
||||
<audio id="audio-element-b" preload="auto" playsinline crossorigin="anonymous"></audio>
|
||||
<audio id="preview-audio"></audio>
|
||||
<audio id="abs-audio"></audio>
|
||||
|
||||
|
||||
+44
-35
@@ -122,6 +122,9 @@ window.addEventListener('load', () => {
|
||||
|
||||
// Wire up audio elements from DOM
|
||||
S.audio = document.getElementById('audio-element');
|
||||
const _audioB = document.getElementById('audio-element-b');
|
||||
// Two fixed audio elements for gapless handoff — S.audio always points at the active one.
|
||||
S._audioEls = _audioB ? [S.audio, _audioB] : [S.audio];
|
||||
S.previewAudio = document.getElementById('preview-audio');
|
||||
|
||||
const saved = localStorage.getItem('ns_cfg');
|
||||
@@ -134,44 +137,50 @@ window.addEventListener('load', () => {
|
||||
if(window.NS_SERVER_URL?.trim()) { const el=document.getElementById('srv-url'); if(el&&!el.value) el.value=window.NS_SERVER_URL.trim(); }
|
||||
|
||||
document.getElementById('srv-pass').addEventListener('keydown', e => { if(e.key==='Enter') doConnect(); });
|
||||
S.audio.addEventListener('timeupdate', updateProgress);
|
||||
S.audio.addEventListener('ended', onEnded);
|
||||
S.audio.addEventListener('play', () => {
|
||||
S._trackChanging = false;
|
||||
absInterrupt();
|
||||
if (S.previewCurrent) stopPreview(false);
|
||||
setPlayIcon(true);
|
||||
document.getElementById('player-art').classList.add('spinning');
|
||||
if(navigator.mediaSession) navigator.mediaSession.playbackState = 'playing';
|
||||
});
|
||||
S.audio.addEventListener('pause', () => {
|
||||
setPlayIcon(false);
|
||||
document.getElementById('player-art').classList.remove('spinning');
|
||||
// Suppress during track change — src swap fires pause before the new track starts
|
||||
if(!S._trackChanging && navigator.mediaSession) navigator.mediaSession.playbackState = 'paused';
|
||||
});
|
||||
// Listeners are bound to BOTH audio elements so a gapless handoff needs no rebinding.
|
||||
// Handlers that only make sense for the playing element guard with `el !== S.audio`.
|
||||
let _errRetries = 0, _errTimer = null;
|
||||
function bindAudioEl(el) {
|
||||
el.addEventListener('timeupdate', updateProgress);
|
||||
el.addEventListener('ended', onEnded);
|
||||
el.addEventListener('play', () => {
|
||||
S._trackChanging = false;
|
||||
absInterrupt();
|
||||
if (S.previewCurrent) stopPreview(false);
|
||||
setPlayIcon(true);
|
||||
document.getElementById('player-art').classList.add('spinning');
|
||||
if(navigator.mediaSession) navigator.mediaSession.playbackState = 'playing';
|
||||
});
|
||||
el.addEventListener('pause', () => {
|
||||
if (el !== S.audio) return; // ignore the idle standby element during a handoff
|
||||
setPlayIcon(false);
|
||||
document.getElementById('player-art').classList.remove('spinning');
|
||||
// Suppress during track change — src swap fires pause before the new track starts
|
||||
if(!S._trackChanging && navigator.mediaSession) navigator.mediaSession.playbackState = 'paused';
|
||||
});
|
||||
// stalled = browser buffer ran out briefly; let the browser retry naturally.
|
||||
el.addEventListener('play', () => { _errRetries = 0; clearTimeout(_errTimer); }, { capture: true });
|
||||
el.addEventListener('error', () => {
|
||||
if (el !== S.audio) return; // standby/preload errors must not disrupt active playback
|
||||
// Skip if playCurrent() is already handling recovery (_trackChanging = true means
|
||||
// we're mid-transition or waiting for canplay — don't conflict with that)
|
||||
if(!S.queue[S.qIdx] || S._trackChanging) return;
|
||||
_errRetries++;
|
||||
const delay = Math.min(1000 * Math.pow(2, _errRetries - 1), 8000); // 1s, 2s, 4s, 8s
|
||||
clearTimeout(_errTimer);
|
||||
_errTimer = setTimeout(() => {
|
||||
if(!S.queue[S.qIdx] || S._trackChanging) return;
|
||||
S._trackChanging = true;
|
||||
S.audio.load();
|
||||
S.audio.play().catch(() => { S._trackChanging = false; });
|
||||
}, delay);
|
||||
});
|
||||
}
|
||||
S._audioEls.forEach(bindAudioEl);
|
||||
|
||||
S.previewAudio.addEventListener('timeupdate', updatePreviewProgress);
|
||||
S.previewAudio.addEventListener('ended', stopPreview);
|
||||
|
||||
// stalled = browser buffer ran out briefly; let the browser retry naturally.
|
||||
// The watchdog below catches genuine long freezes.
|
||||
let _errRetries = 0, _errTimer = null;
|
||||
S.audio.addEventListener('play', () => { _errRetries = 0; clearTimeout(_errTimer); }, { capture: true });
|
||||
S.audio.addEventListener('error', () => {
|
||||
// Skip if playCurrent() is already handling recovery (_trackChanging = true means
|
||||
// we're mid-transition or waiting for canplay — don't conflict with that)
|
||||
if(!S.queue[S.qIdx] || S._trackChanging) return;
|
||||
_errRetries++;
|
||||
const delay = Math.min(1000 * Math.pow(2, _errRetries - 1), 8000); // 1s, 2s, 4s, 8s
|
||||
clearTimeout(_errTimer);
|
||||
_errTimer = setTimeout(() => {
|
||||
if(!S.queue[S.qIdx] || S._trackChanging) return;
|
||||
S._trackChanging = true;
|
||||
S.audio.load();
|
||||
S.audio.play().catch(() => { S._trackChanging = false; });
|
||||
}, delay);
|
||||
});
|
||||
|
||||
const _savedVol = parseInt(localStorage.getItem('ns_volume') ?? '', 10);
|
||||
setVolume(isNaN(_savedVol) ? 55 : _savedVol);
|
||||
|
||||
|
||||
+46
-12
@@ -276,10 +276,19 @@ function _setAudioSession() {
|
||||
try { if(navigator.audioSession) navigator.audioSession.type = 'playback'; } catch {}
|
||||
}
|
||||
|
||||
// ─── PRELOAD — shadow Audio element actually buffers the next track ──────────
|
||||
// ─── PRELOAD — the standby audio element buffers the next track ──────────────
|
||||
// Buffering into the *standby* element (not a throwaway) lets playCurrent() hand
|
||||
// playback over to it gaplessly: the active element never empties, so the OS media
|
||||
// tile doesn't flicker on skip. Falls back to a source-swap when not preloaded.
|
||||
let _preUrl = '';
|
||||
let _preId = '';
|
||||
let _preAudio = null;
|
||||
|
||||
/** The audio element that is NOT currently active (or null if there's only one). */
|
||||
function _standbyEl() {
|
||||
const els = S._audioEls;
|
||||
if (!els || els.length < 2) return null;
|
||||
return els.find(e => e !== S.audio) || null;
|
||||
}
|
||||
|
||||
function _nextIdx() {
|
||||
if(S.repeat === 'one') return S.qIdx;
|
||||
@@ -294,13 +303,12 @@ function _preloadNext() {
|
||||
if(ni < 0) return;
|
||||
const next = S.queue[ni];
|
||||
if(!next || _preId === next.id) return;
|
||||
const standby = _standbyEl();
|
||||
if(!standby) return;
|
||||
_preId = next.id;
|
||||
_preUrl = streamUrl(next.id);
|
||||
// Real Audio preload — actually buffers the stream so canplay fires instantly
|
||||
if(_preAudio) { _preAudio.src = ''; _preAudio = null; }
|
||||
_preAudio = new Audio();
|
||||
_preAudio.preload = 'auto';
|
||||
_preAudio.src = _preUrl;
|
||||
standby.src = _preUrl; // preload="auto" → the element buffers it for a gapless handoff
|
||||
try { standby.load(); } catch {}
|
||||
if(next.coverArt) {
|
||||
[256, 512, 1024].forEach(size => {
|
||||
const img = new Image();
|
||||
@@ -311,7 +319,8 @@ function _preloadNext() {
|
||||
|
||||
function _clearPreload() {
|
||||
_preId = ''; _preUrl = '';
|
||||
if(_preAudio) { _preAudio.src = ''; _preAudio = null; }
|
||||
const standby = _standbyEl();
|
||||
if(standby) { try { standby.pause(); standby.removeAttribute('src'); standby.load(); } catch {} }
|
||||
}
|
||||
|
||||
// ─── PLAY HISTORY (for prev-in-shuffle) ──────────────────────────────────────
|
||||
@@ -397,10 +406,6 @@ export function playCurrent() {
|
||||
renderQueue();
|
||||
_scheduleScrobble(s.id, s.duration);
|
||||
|
||||
const src = (_preId === s.id && _preUrl) ? _preUrl : streamUrl(s.id);
|
||||
_clearPreload();
|
||||
S.audio.src = src;
|
||||
|
||||
const _resetFlag = () => { if (_playGen === gen) S._trackChanging = false; };
|
||||
|
||||
const _applySession = () => {
|
||||
@@ -409,6 +414,35 @@ export function playCurrent() {
|
||||
setTimeout(_preloadNext, 2000);
|
||||
};
|
||||
|
||||
// ── Gapless handoff: if the standby element already buffered THIS track, switch
|
||||
// playback to it instead of reloading the source. The active element never empties,
|
||||
// so the OS media tile stays put (and the skip is instant). ──
|
||||
const standby = _standbyEl();
|
||||
if (standby && _preId === s.id && standby.readyState >= 2) {
|
||||
const old = S.audio;
|
||||
standby.currentTime = 0;
|
||||
standby.volume = old.volume; standby.muted = old.muted; standby.playbackRate = old.playbackRate || 1;
|
||||
S.audio = standby; // the active element is now the preloaded one
|
||||
_preId = ''; _preUrl = '';
|
||||
try { old.pause(); } catch {} // 'pause' is ignored for the now-inactive element
|
||||
_setAudioSession();
|
||||
S.audio.play()
|
||||
.then(() => { S._trackChanging = false; _applySession(); })
|
||||
.catch(() => {
|
||||
// Handoff playback failed — recover with a fresh source load on this element.
|
||||
if (_playGen !== gen) return;
|
||||
S.audio.src = streamUrl(s.id);
|
||||
try { S.audio.load(); } catch {}
|
||||
S.audio.play().then(() => { S._trackChanging = false; _applySession(); }).catch(_resetFlag);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Fallback: classic source swap on the current element (unchanged) ──
|
||||
const src = (_preId === s.id && _preUrl) ? _preUrl : streamUrl(s.id);
|
||||
_clearPreload();
|
||||
S.audio.src = src;
|
||||
|
||||
let _guardTimer = null;
|
||||
let _canplayFn = null;
|
||||
|
||||
|
||||
Reference in new issue
Block a user