speechSynthesis.getVoices() returns empty array on Windows

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

The speechSynthesis.getVoices() function in JavaScript is used to retrieve the list of available speech synthesis voices on the user's system. However, on some platforms, including Windows, the list of voices may initially appear to be empty due to the way the Web Speech API is implemented.

On Windows, the voices for speech synthesis are provided by the operating system's Text-to-Speech (TTS) engine. If the voices are not immediately available when calling speechSynthesis.getVoices(), it could be because the TTS engine is not yet fully loaded or initialized.

To work around this issue, you can listen for the voiceschanged event, which is fired when the list of available voices changes. This event indicates that the TTS engine has finished loading the voices. You can use it like this:

javascript
function onVoicesChanged() {
var voices = speechSynthesis.getVoices();
// Now you have the list of available voices.
// Do whatever you want with the voices array here.
}

// Add an event listener for the voiceschanged event.
// This will ensure that the event is triggered when the voices are available.
speechSynthesis.onvoiceschanged = onVoicesChanged;

By waiting for the voiceschanged event, you ensure that the list of voices is populated before you access it.

Keep in mind that the availability of voices depends on the user's system configuration and the installed TTS engines. If the getVoices() method still returns an empty array, it could indicate that there are no TTS engines installed on the system. In that case, the user would need to install a TTS engine to use speech synthesis.