JSFiddle - React, Tailwind, and code Playground
by Rene Kriest
HTML
<section id='result'></section>
JavaScript
// Web Speech API: getVoice method
// ===============================
// The SpeechSynthesis's getVoice method is a little tricky due to the fact that the docs
// yet don't mention that it works asynchronously.
//
// Calling it synchronously will return an empty array which is not desired.
//
// Here I show you how to properly receive the voices by using the voiceschanged event.
// The voiceschanged event is so far only mentioned in the errata and hasn't been
// incorporated into the docs yet.
$('#result').text('');
function getVoices() {
return new Promise(function (resolve, reject) {
speechSynthesis.onvoiceschanged = function (e) {
var voices = this.getVoices();
if (voices.length > 0)
resolve(voices); // Array with Voices
else
reject(voices); // Empty Array
};
speechSynthesis.getVoices();
});
}
getVoices().then(function (voices) {
$('#result').text(voices);
}, function (voices) {
$('#result').text(voices);
});
// Further readings:
// https://code.google.com/p/chromium/issues/detail?id=334847
// https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html
// https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi-errata.html