diff --git a/lib/mi-voice-bridge.ts b/lib/mi-voice-bridge.ts index a45e6d05..4cabf7aa 100644 --- a/lib/mi-voice-bridge.ts +++ b/lib/mi-voice-bridge.ts @@ -88,12 +88,12 @@ export class MiVoiceBridge { // ── Bridge TTS ── - #ensureAudioCtx(): AudioContext { + async #ensureAudioCtx(): Promise { if (!this.#audioCtx || this.#audioCtx.state === "closed") { this.#audioCtx = new AudioContext(); } if (this.#audioCtx.state === "suspended") { - this.#audioCtx.resume(); + try { await this.#audioCtx.resume(); } catch { /* gesture may be required */ } } return this.#audioCtx; } @@ -158,14 +158,18 @@ export class MiVoiceBridge { } catch { /* ignore bad header */ } const mp3Bytes = buf.slice(4 + headerLen); - const ctx = this.#ensureAudioCtx(); + const ctx = await this.#ensureAudioCtx(); const audioBuffer = await ctx.decodeAudioData(mp3Bytes.slice(0)); // slice to copy const source = ctx.createBufferSource(); source.buffer = audioBuffer; const gain = ctx.createGain(); gain.gain.value = gainValue; - source.connect(gain).connect(ctx.destination); + source.connect(gain); + gain.connect(ctx.destination); this.#currentSource = source; + if (ctx.state === "suspended") { + try { await ctx.resume(); } catch { /* ignore */ } + } source.onended = () => { this.#currentSource = null;