gpt4 book ai didi

javascript - 如何等到循环内的语音结束?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:39:43 24 4
gpt4 key购买 nike

我想暂停/等待 for 循环,直到 window.speechSynthesis.speak(audio) 完成阅读文本,然后转到下一次迭代。我有以下代码:

 var all = "Oak is strong and also gives shade \n \
Cats and dogs each hate the other \n \
The pipe began to rust while new \n Bye."


sentences = all.split('\n')
for (i = 0; i < sentences.length; i++) {
sentence = sentences[i]
console.log(sentences[i]);
audio = new SpeechSynthesisUtterance(sentence)
window.speechSynthesis.speak(audio)
}

现在我想要的是,一旦每个 sentences[i] 被打印出来。在 window.speechSynthesis.speak(audio) 完成之前,下一个 sentences[i] 不会被打印,一旦语音结束,那么 sentences[i] 将为下一次迭代打印。

那么我怎样才能让循环等到一个函数没有完成呢?

注意:我可以让它等待一个恒定的时间,但我想要一个动态等待,即等待时间应该与window.speechSynthesis.speak(audio) 需要时间来完成文本。

最佳答案

对于 SpeechSynthesisUtterance API,有一个 onend 事件,您可以使用它 ( SpeechSynthesisUtterance: end event)。

所以我猜你可以在 onend 中添加一个事件监听器,你需要在其中调用下一次迭代的代码。一种好的技术是在异步情况下使用 Promise 来等待回调完成。我根据您的问题为上述案例创建了一个工作示例:

(function() {
play();

async function play() {
let all = "Oak is strong and also gives shade \n \
Cats and dogs each hate the other \n \
The pipe began to rust while new \n Bye.";

sentences = all.split('\n');

for (i = 0; i < sentences.length; i++) {
await getNextAudio(sentences[i]);
}

async function getNextAudio(sentence) {
console.log(sentence);
let audio = new SpeechSynthesisUtterance(sentence);
window.speechSynthesis.speak(audio);

return new Promise(resolve => {
audio.onend = resolve;
});
}
}
})();

如果您对更多细节感兴趣,请访问以下链接以进一步阅读:

  1. Promise
  2. SpeechSynthesis.speak()
  3. SpeechSynthesisUtterance.onend
  4. async function

该解决方案就像魅力一样有效,希望对您有所帮助!

关于javascript - 如何等到循环内的语音结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58049491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com