TTS Javascript new SpeechSynthesisUtterance() and speechSynthesis.getVoices()
Create a TTS - Text to Speech / Voice app using javascript. Get and Show available voices
<label for="voices">Select a voice:</label>
<select id="voices"></select>
<div id="show">
</div>
<script>
window.onload = function() {
const greeting = "How are you?";
// Create a new SpeechSynthesisUtterance object
const synth = new SpeechSynthesisUtterance();
synth.text = greeting;
// Get the select element
const select = document.getElementById('voices');
// Get the list of available voices
const voices = speechSynthesis.getVoices();
// Populate the select element with the voices
for (let i = 0; i < voices.length; i++) {
const option = document.createElement('option');
option.value = voices[i].name;
option.textContent = voices[i].name;
select.appendChild(option);
}
// Create a play button element
const playButton = document.createElement('button');
playButton.textContent = 'Play';
// Add an event listener to the play button that starts the speech synthesis when clicked
playButton.addEventListener('click', function() {
// Set the voice of the synth to the selected voice
synth.voice = voices.find(voice => voice.name === select.value);
speechSynthesis.speak(synth);
});
const element = document.getElementById('show');
element.appendChild(playButton);
element.appendChild(document.createTextNode(greeting));
}
</script>