今天看到一个语音合成的API,调用的时候遇到一些问题
//初始化speechSynthesis API
const synth = window.speechSynthesis;
let voices = [];
const getVoices = () => {
voices = synth.getVoices();
console.log(voices)
}
getVoices();
我想把系统支持的语音列表存到voices数组里,但是返回的是一个空数组
查了一下MDN文档,按照他们的例子把代码改成这样:
//初始化speechSynthesis API
const synth = window.speechSynthesis;
let voices = [];
const getVoices = () => {
voices = synth.getVoices();
console.log(voices)
}
getVoices();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = getVoices;
}
就增加了一个判断,但是为什么这样就可以了我也不明白,网上查了下可能是异步?完全不知道里面的逻辑是怎样的,哪位大佬能否用通俗易懂的方式帮我解释一下,无比感谢:D
对,就是异步的。
根据 W3C 对于 Web Speech API 的规范(传送门:(https://dvcs.w3.org/hg/speech...),语音列表是异步加载的(因为依赖于网络服务端合成),加载完毕后会触发
voiceschanged
事件。