我正在尝试使用Speechsynthesis一个简单的示例。

<script>

voices = window.speechSynthesis.getVoices()
var utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[4];
utterance.lang = voices[4].lang;
window.speechSynthesis.speak(utterance);

</script>

但这会产生一个错误,即声音是不确定的。我发现getVoices()已异步加载。我看到了this答案,并如下所示更新了我的代码以使用回调。
<script>
window.speechSynthesis.onvoiceschanged = function() {
voices = window.speechSynthesis.getVoices()
var utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[4];
utterance.lang = voices[4].lang;
window.speechSynthesis.speak(utterance);
};
</script>

但是由于某种奇怪的原因,该文本被说了三遍而不是一遍。我该如何解决此代码?

最佳答案

我无法复制您的问题,但是请尝试添加事件监听器,以便在加载声音后运行您的函数。

let voices, utterance;

function speakVoice() {
voices = this.getVoices();
utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[1];
speechSynthesis.speak(utterance);
};

speechSynthesis.addEventListener('voiceschanged', speakVoice);

09-25 18:15