-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
47 lines (37 loc) · 1.28 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const playButton = document.getElementById('play-button');
const pauseButton = document.getElementById('pause-button');
const stopButton = document.getElementById('stop-button');
const textInput = document.getElementById('text');
const speedInput = document.getElementById('speed');
let currentCharater;
playButton.addEventListener('click', () => playText(textInput.value));
pauseButton.addEventListener('click', pauseText);
stopButton.addEventListener('click', stopText);
speedInput.addEventListener('input', () => {
stopText();
playText(utterance.text.substring(currentCharater));
});
const utterance = new SpeechSynthesisUtterance();
utterance.addEventListener('end', () => {
textInput.disabled = false;
});
utterance.addEventListener('boundary', (e) => {
currentCharacter = e.charIndex;
});
function playText(text) {
if (speechSynthesis.paused && speechSynthesis.speaking) {
return speechSynthesis.resume();
}
if (speechSynthesis.speaking) return;
utterance.text = text;
utterance.rate = speedInput.rate || 1;
textInput.disabled = true;
speechSynthesis.speak(utterance);
}
function pauseText() {
if (speechSynthesis.speaking) speechSynthesis.pause();
}
function stopText() {
speechSynthesis.resume();
speechSynthesis.cancel();
}