From e25d91f0256d35c3fddf97d2df2e3fff4e75de5e Mon Sep 17 00:00:00 2001 From: kron Date: Thu, 13 Nov 2025 16:29:21 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E8=BD=BD=E7=AD=96=E7=95=A5=E8=B0=83?= =?UTF-8?q?=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/audioManager.js | 80 ++++++++++++++++++++++++++++++++------------- 1 file changed, 57 insertions(+), 23 deletions(-) diff --git a/src/audioManager.js b/src/audioManager.js index 08832df..ec6b25a 100644 --- a/src/audioManager.js +++ b/src/audioManager.js @@ -300,17 +300,6 @@ class AudioManager { // 播放指定音频或音频数组(数组则按顺序连续播放) play(input) { - // 离线:缓存播放意图(可为字符串或数组),待网络恢复后自动播放 - if (!this.networkOnline) { - this.pendingPlayKey = input; - debugLog( - `网络不可用,记录播放意图: ${ - Array.isArray(input) ? input.join(",") : input - }` - ); - return; - } - // 再次调用 play:打断前面所有声音与队列 this.stopAll(); this.isSequenceRunning = false; @@ -339,9 +328,14 @@ class AudioManager { // 内部方法:播放单个 key _playSingle(key, forceStopAll = false) { if (!this.networkOnline) { - this.pendingPlayKey = key; - debugLog(`网络不可用,记录播放意图: ${key}`); - return; + const audio = this.audioMap.get(key); + const isReady = this.readyMap && this.readyMap.get(key); + // 离线但已就绪:允许直接播放;未就绪则记录等待重连 + if (!audio || !isReady) { + this.pendingPlayKey = key; + debugLog(`网络不可用,记录播放: ${key}`); + return; + } } if (forceStopAll) { @@ -451,16 +445,33 @@ class AudioManager { } catch (_) {} } - // 重连回调:重建全部音频后,重放上一次的播放意图 + // 重连回调:重建全部音频后,重放上一次的播放 onNetworkRestored() { - this.reinitializeOnReconnect(); - if (this.pendingPlayKey) { - const key = this.pendingPlayKey; - this.pendingPlayKey = null; - // 避免与初始化竞态,轻微延迟后播放 - setTimeout(() => { - this.play(key); - }, 20); + // 网络恢复后,仅继续加载未就绪或缺失的音频,已就绪的不动,保证离线可播的缓存不被重置 + const keys = Object.keys(audioFils); + const needLoad = keys.filter( + (k) => !this.readyMap.get(k) || !this.audioMap.has(k) + ); + + if (needLoad.length > 0) { + this.loadKeysSequentially(needLoad, () => { + if (this.pendingPlayKey) { + const pending = this.pendingPlayKey; + this.pendingPlayKey = null; + setTimeout(() => { + this.play(pending); + }, 20); + } + }); + } else { + // 没有需要加载的音频,直接处理待播放 + if (this.pendingPlayKey) { + const pending = this.pendingPlayKey; + this.pendingPlayKey = null; + setTimeout(() => { + this.play(pending); + }, 20); + } } } @@ -470,6 +481,29 @@ class AudioManager { this.initAudios(); } + // 按自定义列表串行加载音频(避免并发过多) + loadKeysSequentially(keys, onComplete) { + let idx = 0; + const next = () => { + if (idx >= keys.length) { + if (onComplete) onComplete(); + return; + } + const k = keys[idx++]; + // 已存在但未就绪:重载;不存在:创建 + if (this.audioMap.has(k)) { + this.retryLoadAudio(k); + } else { + this.createAudio(k, () => { + setTimeout(next, 100); + }); + return; // createAudio 内部会触发 next + } + setTimeout(next, 100); + }; + next(); + } + // 手动重新加载指定音频 reloadAudio(key) { if (audioFils[key]) {