Web Speech API
Source: Using the Speech Synthesis Interface of the Web Speech API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
window.addEventListener('load', () => {
let synth, voice;
const speak = text => {
if (!synth || synth.speaking) return;
const utterance = new SpeechSynthesisUtterance(text);
utterance.addEventListener('error', error => console.error(error));
utterance.voice = voice;
synth.speak(utterance);
};
if ('speechSynthesis' in window) {
synth = window.speechSynthesis;
const voices = synth.getVoices();
voice = voices.find(v => v.name === 'Alex');
}
const button = document.getElementById('speakButton');
const demo = () => speak('Hello world');
button.addEventListener('click', demo);
});