为什么SpeechSynthesisUtterance无法选中Microsoft Zira女性语音?
你遇到的问题是两个常见的Web Speech API兼容坑导致的:
- 语音列表加载是异步行为,
speechSynthesis.getVoices()页面初始化阶段调用会返回空数组,只有等浏览器触发voiceschanged事件后才能拿到完整的语音列表 - 微软系统桌面语音在Chromium内核浏览器(Chrome、Edge)中调用要求更严格,需要完全匹配语音名称、对齐语言属性才能正常触发
解决步骤
步骤1:提前缓存语音列表,监听加载完成事件
不要在点击触发朗读的函数中才调用getVoices(),要在页面初始化阶段就监听voiceschanged事件,提前把目标语音缓存下来,避免读取空值。
步骤2:确认语音名称精确匹配
先在浏览器控制台执行以下代码,打印当前环境所有可用语音的完整名称,确认你要调用的Zira语音的实际名称和你写的字符串完全一致(部分精简版Win10中语音名称可能没有Desktop后缀,差一个字符都会匹配失败):
speechSynthesis.getVoices().forEach(v => console.log(v.name))
步骤3:补充语言属性配置
给SpeechSynthesisUtterance实例补充lang属性,设置为en-US和Zira语音的语言对齐,避免浏览器优先按语言匹配默认语音,忽略你设置的voice参数。
步骤4:检查系统语音配置
打开Windows设置→时间和语言→语音,确认「英语(美国)」的语音包已安装,且Microsoft Zira Desktop在可用语音列表中,未安装的话需要先下载对应语音包。
修正后完整代码
<!DOCTYPE html> <html> <head> <script> // 全局缓存目标语音 let ziraVoice = null // 监听语音列表加载完成事件 speechSynthesis.onvoiceschanged = () => { const voices = speechSynthesis.getVoices() ziraVoice = voices.find(voice => voice.name === "Microsoft Zira Desktop - English (United States)") } function myFunction() { // 容错处理,如果语音还没加载完或者没找到,直接返回提示 if (!ziraVoice) { alert('语音未加载完成,请稍后重试') return } const msg = new SpeechSynthesisUtterance() msg.voice = ziraVoice // 补充lang属性对齐语音语言 msg.lang = 'en-US' msg.text = document.getElementById("testDiv").textContent window.speechSynthesis.speak(msg) } </script> </head> <body> <h2>头部引入JavaScript</h2> <div id="testDiv">SQL Managed Instance gives you an instance of SQL Server but removes much of the <b>overhead</b> of managing a <u>virtual machine</u>. Most of the features available in SQL Server are available in SQL Managed Instance. This option is ideal for customers who want to use instance-scoped features and want to move to Azure without rearchitecting their applications.</div> <button type="button" onclick="myFunction()">点击测试</button> </body> </html>
补充说明
你之前测试Google UK English Female语音首次点击不生效、后续生效的原因,就是首次点击时语音列表还没加载完成,匹配返回空值浏览器自动用默认男声,后续加载完成后匹配到对应语音就正常生效了。
如果按照上面的步骤调整后Zira语音还是不生效,就是当前版本的Chromium浏览器和微软系统桌面语音的兼容问题,属于已知的实验性API兼容边界,可换用浏览器自带的云端语音(比如你测试过的Google系列语音)规避。
内容的提问来源于stack exchange,提问作者nam
相关产品推荐
相关产品推荐

