speechSynthesis.getVoices()在Windows上返回空数组

Mel*_*ham 6 javascript windows arrays voice speech-synthesis

我正在制作一个Chrome扩展程序,其中正在使用语音合成。当我speechSynthesis.getVoices()控制台中键入内容时,我会得到21种不同声音数组。大!

当我console.log()在JavaScript代码中的同一行时,在控制台中出现一个空数组。怎么了,我不知道!

Mel*_*ham 18

正如@CertainPerformance 在评论中指出的那样,当页面加载时,异步填充 voices 数组需要一些时间。因此,在页面加载后立即将数组登录到控制台时,我们会看到一个空数组...

为了解决这个问题,我们在一段时间后(比如 10 或 50 毫秒)控制台记录它:

setTimeout(() => {
    console.log(window.speechSynthesis.getVoices());
}, <time_in_ms>);
Run Code Online (Sandbox Code Playgroud)

如果你想用 实现同样的效果Promises,那么,代码如下:

function setSpeech() {
    return new Promise(
        function (resolve, reject) {
            let synth = window.speechSynthesis;
            let id;

            id = setInterval(() => {
                if (synth.getVoices().length !== 0) {
                    resolve(synth.getVoices());
                    clearInterval(id);
                }
            }, 10);
        }
    )
}

let s = setSpeech();
s.then((voices) => console.log(voices));    // Or any other actions you want to take...
Run Code Online (Sandbox Code Playgroud)

这里,在每个时间间隔后,我们检查返回的voices数组是否getVoices()为空。如果不是,我们最终会解决承诺......

  • 是的!window.speechSynthesis.onvoiceschanged = () =&gt;{ console.warn('语音已准备就绪',window.speechSynthesis.getVoices()); }; (5认同)