以下HTML在第一次单击时在控制台中显示空数组:
<!DOCTYPE html>
<html>
<head>
<script>
function test(){
console.log(window.speechSynthesis.getVoices())
}
</script>
</head>
<body>
<a href="#" onclick="test()">Test</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
在第二次单击中,您将获得预期的列表.
如果添加onload事件来调用此函数(<body onload="test()">),则可以在第一次单击时获得正确的结果.请注意,第一次调用onload仍然无法正常工作.它在页面加载时返回空,但后续工作.
问题:
由于它可能是测试版中的错误,我放弃了"为什么"的问题.
现在,问题是您是否要window.speechSynthesis在页面加载时访问:
speechSynthesis在页面加载时确保它会加载?背景和测试:
我正在测试Web Speech API中的新功能,然后我在我的代码中遇到了这个问题:
<script type="text/javascript">
$(document).ready(function(){
// Browser support messages. (You might need Chrome 33.0 Beta)
if (!('speechSynthesis' in window)) {
alert("You don't have speechSynthesis");
}
var voices = window.speechSynthesis.getVoices();
console.log(voices) // []
$("#test").on('click', function(){
var voices = window.speechSynthesis.getVoices();
console.log(voices); // …Run Code Online (Sandbox Code Playgroud) 我正在开发一个应用程序,要求我在Web浏览器中使用文本到语音.我正在使用HTML5语音合成.在谷歌浏览器上,代码运行正常,所有可用的声音都使用| getVoices()|列出,但在Firefox中根本没有列出语音.我在Firefox 56.0(Ubuntu)上测试我的代码.
在通过互联网搜索时,我确实遇到了一个StackOverflow 答案,该答案表明应该在| onVoiceChanged |之后调用getVoices()函数.事件
window.speechSynthesis.onvoiceschanged = function() {
window.speechSynthesis.getVoices();
...
};
Run Code Online (Sandbox Code Playgroud)
我正在以上述方式调用该呼叫,它在Chrome中可以正常工作,但在Firefox上则不行.
另一个StackOverflow回答建议我启用| media.webspeech.synth.enabled | 在about:配置Firefox,但在我的Firefox中首选| media.webspeech.synth.enabled | 已经设置为true.
我查看了MDN文档https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis/getVoices,此页面上的示例在Firefox中没有运行,但在Chrome中运行良好.我发现CanIUse.com列出了Firefox 55以后支持的SpeechSynthesis,但它对我不起作用.
还演示由Mozilla开发者网络来演示语音合成失败对我的Firefox浏览器,但在谷歌浏览器运行正常.我在网上广泛搜索了一个解决方案,但找不到一个.有人可以在这里指出我正确的方向.