diff --git a/src/audioManager.js b/src/audioManager.js index 1d3d051..a61ae55 100644 --- a/src/audioManager.js +++ b/src/audioManager.js @@ -79,6 +79,8 @@ class AudioManager { this.currentPlayingKey = null; this.retryCount = new Map(); this.maxRetries = 3; + // 显式授权播放标记,防止 iOS 在设置 src 后误播 + this.allowPlayMap = new Map(); // 串行加载相关属性 this.audioKeys = []; @@ -136,8 +138,20 @@ class AudioManager { createAudio(key, callback) { const src = audioFils[key]; const audio = uni.createInnerAudioContext(); - audio.src = src; audio.autoplay = false; + audio.src = src; + + // 初始化为不允许播放,只有显式 play() 才允许 + this.allowPlayMap.set(key, false); + + // 防止 iOS 误播:非授权播放立刻停止 + audio.onPlay(() => { + if (!this.allowPlayMap.get(key)) { + try { + audio.stop(); + } catch (_) {} + } + }); // 设置加载超时 const loadTimeout = setTimeout(() => { @@ -148,6 +162,10 @@ class AudioManager { // 监听加载状态 audio.onCanplay(() => { + // 保险:预加载阶段确保不播放 + try { + audio.pause(); + } catch (_) {} clearTimeout(loadTimeout); debugLog(`音频 ${key} 已加载完成`); this.retryCount.set(key, 0); @@ -157,6 +175,7 @@ class AudioManager { audio.onError((res) => { clearTimeout(loadTimeout); debugLog(`音频 ${key} 加载失败:`, res.errMsg); + this.allowPlayMap.set(key, false); this.handleAudioError(key); if (callback) callback(); }); @@ -166,6 +185,7 @@ class AudioManager { if (this.currentPlayingKey === key) { this.currentPlayingKey = null; } + this.allowPlayMap.set(key, false); }); // 监听播放停止事件 @@ -173,6 +193,7 @@ class AudioManager { if (this.currentPlayingKey === key) { this.currentPlayingKey = null; } + this.allowPlayMap.set(key, false); }); this.audioMap.set(key, audio); @@ -215,8 +236,6 @@ class AudioManager { // 播放指定音频 play(key) { - const pages = getCurrentPages(); - if (pages.length <= 1) return; // 如果有正在播放的音频,先停止 if (this.currentPlayingKey) { this.stop(this.currentPlayingKey); @@ -225,6 +244,8 @@ class AudioManager { const audio = this.audioMap.get(key); if (audio) { console.log("播放音频:", key); + // 显式授权播放并立即播放 + this.allowPlayMap.set(key, true); audio.play(); this.currentPlayingKey = key; } else { @@ -238,6 +259,7 @@ class AudioManager { const audio = this.audioMap.get(key); if (audio) { audio.stop(); + this.allowPlayMap.set(key, false); if (this.currentPlayingKey === key) { this.currentPlayingKey = null; }