为什么 Google Chrome 中的 voiceSynthesis.getVoices() 返回空列表?

elp*_*phe 6 javascript dom google-chrome speech

我想要访问桌面 Chrome、Safari 和 Firefox 上 SpeechSynthesis API 的一部分的语音列表。如果我在每个浏览器中打开一个新选项卡,然后通过控制台运行:

speechSynthesis.getVoices()
Run Code Online (Sandbox Code Playgroud)

...我期望返回一个包含“SpeechSynthesisVoice”对象(即可用语音)的数组。Firefox 和 Safari 的行为符合预期,但在 Chrome 中,第一次调用 getVoices() 返回一个空数组。我必须再次调用该方法才能接收预期的填充数组。

为什么 Chrome 会有这样的表现?它是否对某些 Web API 进行某种延迟加载?请帮助我理解。

Pau*_*kin 8

发生这种情况是因为 SpeechSynthesis API 允许使用远程服务器进行语音合成,并且 Chrome 会从 Google 服务器请求语音列表。要解决此问题,您需要等待语音加载,然后再次请求它们。

为此,您应该侦听voicechanged事件,然后初始化程序的逻辑:

speechSynthesis.addEventListener("voiceschanged", () => {
  const voices = speechSynthesis.getVoices()
})
Run Code Online (Sandbox Code Playgroud)