如何在语音合成中改变声音? [英] How to change voice in Speech Synthesis?

查看:184
本文介绍了如何在语音合成中改变声音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 语音合成 的简单示例.

I am trying out a simple example with 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() 是异步加载的.我看到了这个答案并更新了我的代码,如下所示以使用回调.

But this gives an error that voices is undefined. I found that getVoices() is loaded async. I saw this answer and updated my code as shown below to use callback.

<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>

但是由于一些奇怪的原因,文本被朗读了三遍而不是一次.如何修复此代码?

But due to some strange reason, the text is spoken three times instead of one. How can I fix this code?

推荐答案

我无法复制您的问题,但请尝试添加一个事件侦听器,以便您的函数在语音加载后运行.

I can't replicate your issue, but try adding an event listener so that your function runs after the voices are loaded.

let voices, utterance;

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

speechSynthesis.addEventListener('voiceschanged', speakVoice);

这篇关于如何在语音合成中改变声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆