-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathspeaker.js
78 lines (73 loc) · 2.56 KB
/
speaker.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
javascript:'READ SELECTED';
(function () {
'use strict';
var sayit = function () {
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[0];
msg.volume = 1;
msg.rate = 1.15;
msg.pitch = 1;
msg.onstart = function (event) {
console.log('started');
};
msg.onend = function (event) {
console.log('Finished in ' + event.elapsedTime + ' seconds.');
};
msg.onerror = function (event) {
console.log('Errored ' + event);
};
msg.onpause = function (event) {
console.log('paused ' + event);
};
msg.onboundary = function (event) {
console.log('onboundary ' + event);
};
return msg;
};
var speekResponse = function (text) {
if (!window.speechSynthesis.getVoices().length) {
setTimeout(() => speekResponse(text), 1000);
return;
}
window.speechSynthesis.cancel();
var sentences = text.split('.');
for (var i = 0; i < sentences.length; i++) {
var toSay = sayit();
toSay.text = sentences[i];
window.speechSynthesis.speak(toSay);
}
};
function addPauses(sel) {
var el = document.createElement('div');
el.appendChild(sel.getRangeAt(0).cloneContents());
for (var i = 0; i < 10; i++) {
addMissingDots(el);
}
return el;
}
function addMissingDots(el) {
var els = el.querySelectorAll('p, li, ol, h1, h2, h3, h4, h5, h6, h7, div');
for (var i = 0; i < els.length; i++) {
var cont = els[i].textContent;
if (cont.length && cont.substr(cont.length - 1) !== '.') {
els[i].innerHTML += '.';
}
}
return el;
}
function getPDFSelection(callback) {
var embed = document.querySelector('embed');
if (!embed) return;
function handler(event) {
if (event.data.type !== 'getSelectedTextReply') return;
window.removeEventListener('message', handler);
console.log(event.data.selectedText);
callback(event.data.selectedText.split(String.fromCharCode(10)).join(' '));
}
window.addEventListener('message', handler);
embed.postMessage({type: 'getSelectedText'}, String.fromCharCode(42));
}
if (window.getSelection().rangeCount) speekResponse(addPauses(window.getSelection()).textContent);
getPDFSelection(speekResponse);
})();