Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

speechSynthesis.getVoices() returns empty array on Windows [duplicate]

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!

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!

like image 543
Melvin Abraham Avatar asked Mar 27 '18 07:03

Melvin Abraham


1 Answers

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

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

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

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

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

like image 144
Melvin Abraham Avatar answered Oct 11 '22 18:10

Melvin Abraham