speechSynthesis.getVoices()在Windows上返回空数组 [英] speechSynthesis.getVoices() returns empty array on Windows

查看:471
本文介绍了speechSynthesis.getVoices()在Windows上返回空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a Chrome Extension, in which I am using Speech Synthesis. When I type speechSynthesis.getVoices() in the console I get an Array of 21 different voices. Great!

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

When I console.log() the same line within my javascript code, I get an Empty Array in the console. What's the matter, I can't figure out!

推荐答案

正如@CertainPerformance在评论中所指出的,加载页面时,异步地填充Voices数组会花费一些时间..因此,在页面加载后立即将阵列登录到控制台时,我们会看到一个空阵列...

As pointed out by @CertainPerformance in the comments, when a page is loaded, it takes some amount of time to populate the voices array as it does so, asynchronously. Due to which when the array is logged into the console immediately after the page loads, we see an empty array...

为解决此问题,我们会在一段时间(例如10或50毫秒)后控制台对其进行记录:

To fix this, we console log it after some time (say, 10 or 50 ms):

setTimeout(() => {
    console.log(window.speechSynthesis.getVoices());
}, <time_in_ms>);

如果您想通过 Promises 实现相同的目标,则代码如下:

If you want to achieve the same with Promises, then, here's the code:

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...

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

Here, after each time interval, we check whether the voices array returned by getVoices() is empty or not. if it's not, we end up resolving the promise...

这篇关于speechSynthesis.getVoices()在Windows上返回空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆