javascript - 如何在语音合成中改变声音?

标签 javascript text-to-speech speech-synthesis

我正在用 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/

相关文章:

javascript - 使用根导入插件为 Gatsby 中的 NPM 包创建别名

javascript - react 事件 : onMouseUp not firing after onMouseEnter event

text-to-speech - 节日 2.4 : why do some voices not work with singing mode?

audio - 高质量,情感,流畅和可变的文本到语音引擎?

javascript - 将参数传递给嵌套函数

javascript - Breeze 获取实体而不是对象的集合

cocoa-touch - iOS 上的文字转语音

javascript 文本到语音阿拉伯语

mobile - SpeechSynthesisUtterance 在移动浏览器中不起作用

javascript - 语音合成无法让手机safari变声