以下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) 据我所知,在Mac或iOS中,在Safari中均不会触发voiceschanged事件。同样奇怪的是,它似乎也没有在iOS上的Chrome中启动,但是我假设iOS上的Chrome使用与Safari相同的JavaScript引擎。
这是我用来验证的一个演示:http : //jsbin.com/gosaqihi/9/edit?js,控制台(摘自“ 获取语音中的语音列表”,Chrome合成(Web Speech API))
我也尝试过使用addEventListener:
speechSynthesis.addEventListener("voiceschanged", function () {
var voices = speechSynthesis.getVoices(),
keys = Object.keys(voices[0]),
i, j;
document.write("<table border=1><tr>");
for ( i = 0; i < keys.length; i++ ) {
document.write("<td>" + keys[i] + "</td>");
}
document.write("</tr>");
for ( i = 0; i < voices.length; i++ ) {
document.write("</tr>");
for ( j = 0; j < keys.length; j++ ) {
document.write("<td>" + voices[i][keys[j]] + "</td>");
}
document.write("</tr>");
}
document.write("<table>");
}, false);
Run Code Online (Sandbox Code Playgroud)
两种方法(onvoiceschanged,addEventListener)在Windows,Android和Mac的Chrome浏览器中都可以正常运行,但在iOS的Chrome和Mac和iOS的Safari浏览器中无法运行。据我所知,Safari根本不会触发变声事件。
复杂的事情,我实际上没有任何苹果设备,因此我不得不通过让朋友尝试一下来弄清楚。 …