javascript Web Speech API问题

今天看到一个语音合成的API,调用的时候遇到一些问题

//初始化speechSynthesis API
        const synth = window.speechSynthesis;

        let voices = [];

        const getVoices = () => {
            voices = synth.getVoices();
            console.log(voices)
        }

        getVoices();

我想把系统支持的语音列表存到voices数组里,但是返回的是一个空数组
image.png

查了一下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
image.png

image.png

阅读 3.3k
1 个回答

对,就是异步的。

根据 W3C 对于 Web Speech API 的规范(传送门:(https://dvcs.w3.org/hg/speech...),语音列表是异步加载的(因为依赖于网络服务端合成),加载完毕后会触发 voiceschanged 事件。

voiceschanged: Fired when the contents of the SpeechSynthesisVoiceList, that the getVoices method will return, have changed. Examples include: server-side synthesis where the list is determined asynchronously, or when client-side voices are installed/uninstalled.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题