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...
function set_up_speech() { return new Promise(function(resolve, reject) { var synth = window.speechSynthesis; var voices = synth.getVoices(); resolve(voices) }) }
CALLED WITHset_up_speech().then(function(voices) { console.log(voices) });
– Shaunta