-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
62 lines (53 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
//speech synthesis libary
//https://developer.mozilla.org/docs/Web/API/Window/speechSynthesis
const textarea = document.querySelector("textarea"),
voiceList = document.querySelector("select"),
speechBtn = document.querySelector("button");
let synth = speechSynthesis,
isSpeaking = true;
voices();
function voices(){
for(let voice of synth.getVoices()){
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(voice.name === voiceList.value){
utterance.voice = voice;
}
}
synth.speak(utterance);
}
speechBtn.addEventListener("click", e => {
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 " ;
}
}
});