以下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) 尝试在Chrome 33中使用语音合成API时遇到问题.它与较短的文本完美配合,但如果我尝试更长的文本,它就会停在中间.在它停止一次后,语音合成在Chrome中的任何位置都不起作用,直到浏览器重新启动.
示例代码(http://jsfiddle.net/Mdm47/1/):
function speak(text) {
var msg = new SpeechSynthesisUtterance();
var voices = speechSynthesis.getVoices();
msg.voice = voices[10];
msg.voiceURI = 'native';
msg.volume = 1;
msg.rate = 1;
msg.pitch = 2;
msg.text = text;
msg.lang = 'en-US';
speechSynthesis.speak(msg);
}
speak('Short text');
speak('Collaboratively administrate empowered markets via plug-and-play networks. Dynamically procrastinate B2C users after installed base benefits. Dramatically visualize customer directed convergence without revolutionary ROI. Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas. Dramatically …Run Code Online (Sandbox Code Playgroud)