It takes a while for the window.speechSynthesis.getVoices()
method to fully populate. If you call it during page load or even immediately after page load then it will likely return an empty array, []
.
There is a simple fix to this:
window.speechSynthesis.addEventListener('voiceschanged', () => {
console.log(window.speechSynthesis.getVoices());
});
Code language: JavaScript (javascript)
Text-to-Speech Demo
Below is our JavaScript text-to-speech demo that shows an example of using the onvoiceschanged
event and the getVoices()
method to populate a dropdown of voices.
Here is the full source code for the demo:
<div>
<input type="text" id="text-input" />
<select id="voice-select"></select>
<button id="speak">Speak</button>
</div>
<script>
// Get the 'speak' button
var speakButton = document.getElementById('speak');
// Get the text input element
var textInput = document.getElementById('text-input');
// Get the voice select element
var voiceSelect = document.getElementById('voice-select');
// Get the speech synthesis API
var synth = window.speechSynthesis;
// Get the speech synthesis API
var synth = window.speechSynthesis;
window.speechSynthesis.addEventListener('voiceschanged', () => {
// Get the available voices
var voices = synth.getVoices();
// Loop through the voices and create an option for each one
voices.forEach(function(voice) {
var option = document.createElement('option');
option.value = voice.name;
option.innerHTML = voice.name;
voiceSelect.appendChild(option);
});
});
// Attach a click event listener to the button
speakButton.addEventListener('click', function() {
// Create a new utterance for the specified text and voice
var utterance = new SpeechSynthesisUtterance(textInput.value);
// Get the selected voice
var selectedVoice = voiceSelect.selectedOptions[0].value;
// Set the selected voice on the utterance
utterance.voice = synth.getVoices().find(voice => voice.name === selectedVoice);
// Speak the utterance
synth.speak(utterance);
});
</script>
Code language: HTML, XML (xml)
Leave a Reply