Speech Synthesis API
The Speech Synthesis API (part of the Web Speech API) enables you to incorporate text-to-speech (TTS) capabilities into your web applications. It allows the browser to read text out loud.
1. The Controller: speechSynthesis
The entry point is the window.speechSynthesis object. It controls the speech service.
speak(utterance): Adds an utterance to the queue to be spoken.cancel(): Removes all utterances from the queue.pause(): Pauses the speech.resume(): Resumes the speech.speaking: Boolean, true if currently speaking.
2. The Utterance: SpeechSynthesisUtterance
To make the browser speak, you create a SpeechSynthesisUtterance object containing the text and configuration.
const msg = new SpeechSynthesisUtterance("Hello World");
window.speechSynthesis.speak(msg);
3. Configuration
You can customize how the speech sounds.
const msg = new SpeechSynthesisUtterance("I am a robot.");
msg.rate = 1; // Speed (0.1 to 10)
msg.pitch = 1; // Pitch (0 to 2)
msg.volume = 1; // Volume (0 to 1)
msg.lang = 'en-US'; // Language code
window.speechSynthesis.speak(msg);
4. Selecting Voices
Browsers provide different voices. You can retrieve them using getVoices(). Note that voices are loaded asynchronously, so you might need to wait for the voiceschanged event.
let voices = [];
function loadVoices() {
voices = window.speechSynthesis.getVoices();
voices.forEach(voice => {
console.log(`${voice.name} (${voice.lang})`);
});
}
// Chrome loads voices asynchronously
window.speechSynthesis.onvoiceschanged = loadVoices;
5. Events
You can listen for events on the utterance object.
const msg = new SpeechSynthesisUtterance("Reading a long text...");
msg.onstart = () => console.log("Started speaking");
msg.onend = () => console.log("Finished speaking");
window.speechSynthesis.speak(msg);
programming/javascript/vanilla/javascript programming/javascript/vanilla/events