我正在用 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);
关于javascript - 如何在语音合成中改变声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42694586/