级联调用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
相关产品推荐
相关产品推荐

