-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
65 lines (55 loc) · 1.73 KB
/
script.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const textarea = document.querySelector("textarea");
const voiceList = document.querySelector("select");
const speechBtn = document.querySelector("button");
let synth = speechSynthesis,
isSpeaking = true;
voices();
function voices() {
for (let voice of synth.getVoices()) {
// Selecting the Google US English as default voice
let selected = voice.name === "Google US English" ? "selected" : "";
let option = `<option value="${voice.name}" ${selected}>${voice.name} (${voice.lang})</option>`;
voiceList.insertAdjacentHTML("beforeend", option);
}
}
synth.addEventListener("voiceschanged", voices);
function textToSpeech(text) {
let utterance = new SpeechSynthesisUtterance(text);
for (let voice of synth.getVoices()) {
// If the available device voice name is equal to the user selected voice name then set the speech voice to the user selected voice
if (voice.name === voiceList.value) {
utterance.voice = voice;
}
}
// Speak the speech
synth.speak(utterance);
}
speechBtn.addEventListener("click", (e) => {
// Prevent the form submitting.
e.preventDefault();
if (textarea.value !== "") {
if (!synth.speaking) {
textToSpeech(textarea.value);
}
if (textarea.value.length > 80) {
setInterval(() => {
if (!synth.speaking && !isSpeaking) {
isSpeaking = true;
speechBtn.innerText = "Convert To Speech";
} else {
}
}, 500);
if (isSpeaking) {
synth.resume();
isSpeaking = false;
speechBtn.innerText = "Pause Speech";
} else {
synth.pause();
isSpeaking = true;
speechBtn.innerText = "Resume Speech";
}
} else {
speechBtn.innerText = "Convert To Speech";
}
}
});