You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

级联调用MS TTS speakTextAsync()无法同步执行问题求助

解决微软TTS Speech SDK朗读重叠问题的思路

问题根源在于speakTextAsync是基于回调的异步方法,并非Promise兼容API,直接用await无法等待朗读完成,三个调用会几乎同时触发,导致音频重叠。

解决方法

方法1:封装为Promise(推荐)

把speakTextAsync包装成返回Promise的函数,通过监听合成事件来控制执行顺序:

function speakTextAsyncPromise(speechSynth, text) {
  return new Promise((resolve, reject) => {
    // 定义事件处理函数
    const handleCompleted = () => {
      cleanupListeners();
      resolve();
    };
    const handleCanceled = () => {
      cleanupListeners();
      reject(new Error('朗读被取消'));
    };
    const handleError = (event) => {
      cleanupListeners();
      reject(new Error(`朗读出错: ${event.errorDetails}`));
    };
    // 移除监听的辅助函数
    function cleanupListeners() {
      speechSynth.removeEventListener('SynthesisCompleted', handleCompleted);
      speechSynth.removeEventListener('SynthesisCanceled', handleCanceled);
      speechSynth.removeEventListener('SynthesisError', handleError);
    }

    // 绑定事件监听
    speechSynth.addEventListener('SynthesisCompleted', handleCompleted);
    speechSynth.addEventListener('SynthesisCanceled', handleCanceled);
    speechSynth.addEventListener('SynthesisError', handleError);

    // 触发朗读
    speechSynth.speakTextAsync(text);
  });
}

// 按顺序调用
async function f(){
  await speakTextAsyncPromise(speechSynth, "A quick brown fox jumps over the lazy dog");
  await speakTextAsyncPromise(speechSynth, "A quick brown fox jumps over the lazy dog");
  await speakTextAsyncPromise(speechSynth, "A quick brown fox jumps over the lazy dog");
}
f();

方法2:使用回调链

利用speakTextAsync的第二个参数(完成回调),在上一段朗读结束后再触发下一段:

function f() {
  speechSynth.speakTextAsync("A quick brown fox jumps over the lazy dog", () => {
    speechSynth.speakTextAsync("A quick brown fox jumps over the lazy dog", () => {
      speechSynth.speakTextAsync("A quick brown fox jumps over the lazy dog");
    });
  });
}
f();

注意事项

  • 无论哪种方法,都要处理SynthesisCanceled和SynthesisError事件,避免因异常导致后续朗读无法执行。
  • 使用Promise封装时,务必在事件触发后移除监听,防止内存泄漏。

内容的提问来源于stack exchange,提问作者oleh hranat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 18:05:13