-
Notifications
You must be signed in to change notification settings - Fork 2
/
tts.js
339 lines (274 loc) · 10.4 KB
/
tts.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// const fullScreenButton=document.querySelector('#full-screen-button');
const inputText = document.querySelector('#input-text');
const inputRate = document.querySelector('#input-rate');
const inputPitch = document.querySelector('#input-pitch');
const inputVoice = document.querySelector('#input-voice');
const resetButton = document.querySelector('#reset-button');
const speakButton = document.querySelector('#speak-button');
const pauseButton = document.querySelector('#pause-button');
const resumeButton = document.querySelector('#resume-button');
const stopButton = document.querySelector('#stop-button');
const prevButton = document.querySelector('#prev-button');
const nextButton = document.querySelector('#next-button');
const readingText = document.querySelector('#reading-text');
const animation = document.querySelector('.animation-wrapper');
const inputURL = document.querySelector('#input-url');
const fetchButton = document.querySelector('#fetch-button');
const fetchAnimation = document.querySelector('#fetch-animation');
const progressBar = document.querySelector('#progress-bar');
const a2hsButton = document.querySelector('#a2hs');
const lizen = document.querySelector('#lizen');
const playerContainer = document.querySelector('.player-container');
const eyes = document.querySelector('#eyes');
const playingDiv = document.querySelector('#playing-div');
const playingNav = document.querySelector('nav');
const scrollCTA = document.querySelector('#scroll-cta');
const appSection = document.querySelector('#app');
const refershVoices = document.querySelector('#refresh-voices');
const cardCTAs = document.querySelectorAll('.card-cta');
//Setting Variables
let voices = [];
let date = new Date();
let stopAll = false;
let pause = false;
let prev = false;
let next = false;
// pauseButton.disabled=true;
// resumeButton.disabled=true;
prevButton.disabled = true;
nextButton.disabled = true;
pauseButton.style.display = 'none';
resumeButton.style.display = 'none';
animation.style.display = 'none';
playingDiv.style.display = 'none';
playingNav.style.display = 'none';
playerContainer.style.display = 'flex';
// Site Analytics
let telegramMessage = '';
telegramMessage = `Landing Page Vistor$${date.getFullYear()}%20${date.getMonth() + 1}%20${date.getDate()}$${date.getHours()}%20${date.getMinutes()}%20${date.getSeconds()}$${navigator.platform}$${navigator.userAgent}~`;
fetch(`https://api.telegram.org/bot1391541181:AAF86uEn063OXGO7hiNhNtAQVuE7oYoxVCA/sendMessage?chat_id=425970658&text=${telegramMessage}&parse_mode=Markdown`);
const synthObj = window.speechSynthesis;
//Execution Statements and Event Handlers
populateVoices();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoices;
}
scrollCTA.addEventListener('click', function () {
appSection.scrollIntoView();
})
// https://stackoverflow.com/a/40956816
cardCTAs.forEach(function (elem) {
elem.addEventListener("click", function () {
appSection.scrollIntoView();
});
});
fetchButton.addEventListener('click', fetchArticle);
resetButton.addEventListener('click', function () {
inputText.value = "";
inputText.focus();
});
refershVoices.addEventListener('click', function () { location.reload(); })
speakButton.addEventListener('click', function () {
parseSentences();
lizen.disabled = true;
//https://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom
if (scrollCTA.offsetHeight > 0)
readingText.scrollIntoView();
});
lizen.addEventListener('click', function () {
parseSentences();
lizen.disabled = true;
playerContainer.style.display = 'block';
eyes.style.display = 'none';
playingDiv.style.display = 'block';
playingNav.style.display = 'block';
if (scrollCTA.offsetHeight > 0)
readingText.scrollIntoView();
});
stopButton.addEventListener('click', stopAllFunction);
pauseButton.addEventListener('click', function () {
pauseFunction();
});
prevButton.addEventListener('click', function () {
speechSynthesis.cancel();
prev = true;
});
nextButton.addEventListener('click', function () {
speechSynthesis.cancel();
next = true;
});
window.addEventListener('blur', function () {
if (scrollCTA.offsetHeight > 0)
pauseFunction();
});
//FUNCTIONS SECTION
//Fetches and Populates the Voices Array in Alphabetical Order
function populateVoices() {
voices = synthObj.getVoices().sort(function (a, b) {
if (a.name.toUpperCase() < b.name.toUpperCase())
return -1;
else if (a.name.toUpperCase() > b.name.toUpperCase())
return 1;
else
return 0;
});
for (let i = 0; i < voices.length; i++) {
const option = document.createElement('option');
option.textContent = `${voices[i].name} (${voices[i].lang})`;
option.setAttribute('data-voice-name', voices[i].name);
option.setAttribute('data-voice-lang', voices[i].lang);
inputVoice.appendChild(option);
}
}
async function fetchArticle() {
// Function Analytics
telegramMessage = `Used Fetch Option$${date.getFullYear()}%20${date.getMonth() + 1}%20${date.getDate()}$${date.getHours()}%20${date.getMinutes()}%20${date.getSeconds()}$${navigator.platform}$${navigator.userAgent}~`;
fetch(`https://api.telegram.org/bot1391541181:AAF86uEn063OXGO7hiNhNtAQVuE7oYoxVCA/sendMessage?chat_id=425970658&text=${telegramMessage}&parse_mode=Markdown`);
let result = '';
inputText.value = '';
fetchAnimation.style.display = 'block';
website = 'https://article-parser.fly.dev?url=' + inputURL.value;
console.log(website);
console.log(`Fetching from ${website}`);
await fetch(website).then(function (response) {
// The API call was successful!
return response.text();
}).then(function (responseJSON) {
articleRaw = JSON.parse(responseJSON)
// Convert the HTML string into a document object
const parser = new DOMParser();
let doc = parser.parseFromString(articleRaw.content, 'text/html');
// Get the article content tags
let array = doc.querySelectorAll('h1, h2, h3, h4, h5, p, li');
for (element of array) {
console.log(element.textContent);
result += element.textContent + `.
`;
}
}).catch(function (err) {
// There was an error
console.warn('Something went wrong.', err);
});
// console.log(result);
inputText.value = result;
// inputText.scrollIntoView();
fetchAnimation.style.display = 'none';
}
//Parses text content and breaks into sentences
//Loops over sentences and sends to showReadingText
//Handles Previous, Stop, Pause, Resume and Next Buttons
async function parseSentences() {
const selectedVoice = inputVoice.selectedOptions[0].getAttribute('data-voice-name');
if (selectedVoice === '') {
alert("Please select Voice from the list");
pauseButton.style.display = 'none';
speakButton.style.display = 'inline';
return;
}
if (inputText.value === '') {
alert("Text Box is empty! Add some content or fetch from a URL.");
return;
}
// Function Analytics
telegramMessage = `Used Parse and Play Option$${date.getFullYear()}%20${date.getMonth() + 1}%20${date.getDate()}$${date.getHours()}%20${date.getMinutes()}%20${date.getSeconds()}$${navigator.platform}$${navigator.userAgent}~`;
fetch(`https://api.telegram.org/bot1391541181:AAF86uEn063OXGO7hiNhNtAQVuE7oYoxVCA/sendMessage?chat_id=425970658&text=${telegramMessage}&parse_mode=Markdown`);
speakButton.style.display = 'none';
pauseButton.style.display = 'inline';
animation.style.display = 'flex';
prevButton.disabled = false;
nextButton.disabled = false;
let sentences = inputText.value.split(/[.|!|?]+/g);
console.log("Finished parsing sentences!")
for (let i = 0; i < sentences.length; i++) {
if (pause === true) {
await pausedResume();
resumeButton.style.display = 'none';
pauseButton.style.display = 'inline';
animation.style.display = 'flex';
i--;
pause = false;
}
if (prev === true) {
i = i - 2;
prev = false;
}
if (stopAll === true) {
stopAll = false;
break;
}
console.log(`Sentence ${i + 1} sent for reading...`);
progressBar.style.width = `${(i / (sentences.length - 1)) * 100}%`;
await showReadingText(sentences[i]);
}
console.log('Flushing Buttons');
prevButton.disabled = true;
nextButton.disabled = true;
speakButton.style.display = 'inline';
pauseButton.style.display = 'none';
resumeButton.style.display = 'none';
readingText.textContent = '👀';
animation.style.display = 'none';
lizen.disabled = false;
}
//Displays Reading text and calls speaker
//Waits until speaking is over
//Returns promise after completion
async function showReadingText(textPart) {
// let screenLock = new NoSleep();
// screenLock.enable();
// console.log('Screen Locked!');
readingText.textContent = textPart;
// inputVoice.scrollIntoView();
await speaker(textPart);
// screenLock.disable();
// console.log('Screen Unlocked.');
return new Promise(resolve => { resolve(); });
}
//TTS Speaking function
//Returns promise after completing or cancelling TTS speak
function speaker(textPart) {
const speakObj = new SpeechSynthesisUtterance(textPart);
const selectedVoice = inputVoice.selectedOptions[0].getAttribute('data-voice-name');
for (let i = 0; i < voices.length; i++) {
if (selectedVoice === voices[i].name)
speakObj.voice = voices[i];
}
//For blank and undefined text inputs
if (textPart === '' || textPart === undefined)
return new Promise(resolve => { resolve(); });
speakObj.rate = inputRate.value;
speakObj.pitch - inputPitch.value;
synthObj.speak(speakObj);
console.log('Reading: ' + textPart);
return new Promise(resolve => { speakObj.onend = resolve; });
}
//Called by Pause Button
//Stops TTS and sets variable values
function pauseFunction() {
speechSynthesis.cancel();
pause = true;
}
//Called by Stop Button
//Stops TTS and sets variable values
function stopAllFunction() {
speakButton.style.display = 'inline';
animation.style.display = 'none';
speechSynthesis.cancel();
readingText.textContent = '👀';
progressBar.style.width = `${0}%`;
lizen.disabled = false;
stopAll = true;
}
//Called by Resume Button
//Resolves promises for pause wait
function pausedResume() {
resumeButton.style.display = 'inline';
pauseButton.style.display = 'none';
animation.style.display = 'none';
return new Promise(resolve => {
resumeButton.onclick = resolve;
stopButton.onclick = resolve;
prevButton.onclick = resolve;
nextButton.onclick = resolve;
});
}