The Web Speech API speechSynthesis interface enables web applications to generate synthetic voice output from text.
Basic Speech Synthesis
const msg = new SpeechSynthesisUtterance('Hello World!');
window.speechSynthesis.speak(msg);
Customizing Speech Properties
const msg = new SpeechSynthesisUtterance('Welcome to our application');
msg.rate = 1.0; // Speed: 0.1 to 10 (default 1)
msg.pitch = 1.2; // Pitch: 0 to 2 (default 1)
msg.volume = 1.0; // Volume: 0 to 1 (default 1)
msg.lang = 'en-US';
// Event listeners
msg.onstart = () => console.log('Speech playback started');
msg.onend = () => console.log('Speech playback finished');
msg.onerror = (e) => console.error('Speech error:', e);
window.speechSynthesis.speak(msg);
Selecting Installed Voices
window.speechSynthesis.onvoiceschanged = () => {
const voices = window.speechSynthesis.getVoices();
const selectedVoice = voices.find(v => v.lang === 'en-US' && v.name.includes('Google'));
if (selectedVoice) {
msg.voice = selectedVoice;
}
};
Controls
window.speechSynthesis.pause(); // Pause speech playback
window.speechSynthesis.resume(); // Resume paused playback
window.speechSynthesis.cancel(); // Abort and clear speech queue