JavaScript Text-to-Speech (TTS) in 2 Lines of Code

Text-to-speech is the process of converting written text into spoken words. In JavaScript, this can be achieved using the SpeechSynthesis interface, which is part of the Web Speech API. This interface allows you to configure the voice and other properties of the speech, and then speak out a given string of text.

Here is an example of how you can use the SpeechSynthesis interface to create text-to-speech in JavaScript:

let utterance = new SpeechSynthesisUtterance("Hello, world"); window.speechSynthesis.speak(utterance);
Code language: JavaScript (javascript)

The utterance object is created with the text "Hello, world", and then the speak() method is called on the window.speechSynthesis object to start speaking the text.

You can further customize the text-to-speech by setting properties on the utterance object, such as the voice to use, the rate and pitch of the speech, and so on.

You can also listen for events on the utterance object to be notified when the speech starts and ends, or when errors occur.

Demo

Below is a demo where you can enter some text, choose a voice, and press Speak to see how the browser’s text-to-speech sounds.

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.onvoiceschanged = () => { // 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)

References

https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API

https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis/voiceschanged_event


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *