【发布时间】:2020-04-03 17:06:49
【问题描述】:
我已经尝试了在 stackoverflow 上可以找到的所有变体,但我仍然无法在 SpeechSynthesis 上改变声音
下面是独立代码,它用所有可用的声音填充下拉列表,并允许我选择我想要的声音。
不幸的是,这段代码并没有改变声音。此外,在改变声音之前。 msg.voice 为空,即使它已用于列出所有可用的声音。
谁能告诉我代码有什么问题? (console.log(msg.voice); 在被设置之前给出一个空值)
<!doctype html>
<html>
<head>
<SCRIPT>
var msg = new SpeechSynthesisUtterance();
voices = window.speechSynthesis.getVoices();
var numberOfVoices=0;
function Main(){
voiceSelect=document.getElementById("voiceSelect");
setTimeout(getVoicesFunction,2000);
}
function getVoicesFunction(){
msg = new SpeechSynthesisUtterance("hello");
numberOfVoices=0;
speechSynthesis.getVoices().forEach(function(voice) {
var option = document.createElement('option');
option.text = option.value = voice.voiceURI;
voiceSelect.add(option, 0);
numberOfVoices=numberOfVoices+1;
});
voiceSelect.onchange = voiceChange;
}
function voiceChange(){
textToSpeech("this is the old voice");
var selectedOption = this[this.selectedIndex];
selectedVoice = selectedOption.text;
msg = new SpeechSynthesisUtterance();
voices = window.speechSynthesis.getVoices();
msg = new SpeechSynthesisUtterance();
console.log("before change msg.voice");
console.log(msg.voice);
for(i = 0; i < numberOfVoices ; i++) {
if(voices[i].voiceURI === selectedVoice) {
var temp="changing the voice number to "+i;
setTimeout(textToSpeech,2000,temp);
msg.voice = voices[i];
console.log(msg.voice);
var tempVoiceNumber=i;
};
}
setTimeout(textToSpeech,4000,"this is the new voice");
}
function textToSpeech(tspeech){
msg = new SpeechSynthesisUtterance();
msg.text = tspeech;
speechSynthesis.speak(msg);
console.log("speech "+tspeech);
}
</SCRIPT>
</head>
<body onload= "Main()" id= "mainb">
<div id="container">
<select name="Combobox1" size="1" id="voiceSelect">
</select>
</div>
</body>
</html>
【问题讨论】:
-
为什么有这么多的setTimeouts?在这里尝试第一个示例:developer.mozilla.org/en-US/docs/Web/API/…
-
感谢弗雷泽 - 我使用超时,因为根据您的链接的标准方法在没有它们的情况下不起作用。我认为这是 javascript 的异步特性——你会在许多关于语音合成的问题上看到这一点——部分解决方案是延迟时间。我发现 Mozilla 文档 - 或任何其他官方文档都没有提到这一点令人惊讶。例如 voices.length 为零,没有时间延迟。并非其中的所有内容都是必需的,但为了安全起见,我已将它们全部放入,并表明即使有时间延迟,这些费用仍然无法正常工作
-
在链接的示例中,有一个部分带有 onvoiceschanged。这是在不使用超时的情况下获取声音的方法。超时的答案不值得一读。
-
谢谢,但那是我开始使用的那段代码。在三台不同的机器和操作系统上,它会将 voices.length 设为零,除非您设置时间延迟。然后它至少给出了正确的声音长度,以及正确的声音列表。不幸的是,它仍然没有真正改变声音。我意识到我可能做错了什么,这就是为什么我用脚本列出了整个 html
标签: javascript text-to-speech speech-synthesis