-
Notifications
You must be signed in to change notification settings - Fork 1
/
insipio-tts.js
493 lines (382 loc) · 19 KB
/
insipio-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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
(function(){
var pluginName = "insipio-tts";
var plugin = function(){
$lib = AtKit.lib();
var settings = {
"baseURL": "https://core.atbar.org/",
"speechServicesURL": 'https://speech.services.atbar.org/',
"ttsChunkSize": 400
};
// Internationalisation
AtKit.addLocalisationMap("en", {
"tts_title" : "Text to Speech",
"tts_options": "Text to Speech Options",
"tts_converting": "Text to Speech conversion is taking place.",
"tts_timeremaining": "Time Remaining:",
"tts_pleasewait": "Please wait...",
"tts_playpause" : "Play / Pause",
"tts_rewind": "Rewind",
"tts_stop": "Stop & Close TTS",
"tts_error": "Error",
"tts_overloaded": "The server is currently over capacity for text to speech conversions. Please try again later.",
"tts_problem": "Something went wrong while we were converting this page to speech. Please try again shortly.",
"tts_servererror": "An error occurred on the server. Please try again later.",
"tts_seconds": "seconds",
"tts_explain": "To use the text to speech feature with selected text, please first select the text on this page that you would like to convert. After you have done this, click the Text to Speech button, and select the 'selected text' option.",
"tts_select_voice": "Highlight text and select a voice",
"tts_male": "Male",
"tts_female": "Female"
});
AtKit.addLocalisationMap("ar", {
"tts_title" : "تحويل النصوص الي مادة مسموعة",
"tts_options":"خيارات نطق النص",
"tts_converting":"جارية حالياً عملية نطق النص",
"tts_timeremaining": "الوقت المتبقي",
"tts_pleasewait":"الرجاء الانتظار...",
"tts_playpause":"تشغيل/إيقاف مؤقت",
"tts_rewind":"إعادة",
"tts_stop":"إيقاف",
"tts_error":"خطأ",
"tts_overloaded":"فاقت عمليات نطق النصوص سعة الخادم. الرجاء المحاولة لاحقاً.",
"tts_problem":"حدث خطأ أثناء عملية نطق الصفحة. الرجاء المحاولة بعد قليل.",
"tts_servererror": "حدث خطأ في الخادم. الرجاء المحاولة لاحقاً.",
"tts_seconds":"ثوانٍ",
"tts_explain":"لاستخدام خاصية نطق النص، الرجاء تحديد النص المراد تحويله على هذه الصفحة. بعد ذلك اضغط زر نطق النص، واضغط خيار "النص المحدد".",
"tts_select_voice": "قم بتظليل النص واختيار الصوت",
"tts_male": "مذكر",
"tts_female": "مؤنث"
});
// Text to speech
var TTSDialogs = {
"options": {
"title": AtKit.localisation("tts_options"),
"body": AtKit.localisation("tts_select_voice") + " <br /><button id=\"sbStartTTSSelectionMale\"> " + AtKit.localisation("tts_male") + "</button> <button id=\"sbStartTTSSelectionFemale\"> " + AtKit.localisation("tts_female") + "</button>"
},
"starting": {
"title": AtKit.localisation("tts_title"),
"body": "<center>" + AtKit.localisation("tts_converting") + " <br /><img src='" + AtKit.getPluginURL() + "images/loadingbig.gif' /><br />"+ AtKit.localisation("tts_timeremaining") +" <div id='sbttstimeremaining'>...</div><br />" + AtKit.localisation("tts_pleasewait") + " </center>"
}
};
var TTSFunctions = {};
/*var TTSExtendedObject = {
clickEnabled: true,
positition: "",
playingItem: "",
"TTSButtons": {
'ttsPlay': {
'tooltip': AtKit.localisation("tts_playpause"),
'icon': AtKit.getPluginURL() + "images/control-pause.png",
'fn': function(){
var targetObj = ($lib.browser == "msie") ? swfobject.getObjectById(AtKit.get('ATAudioPlayerID')) : window.document['audioe'];
targetObj.sendEvent('play');
}
},
'ttsRewind': {
'tooltip': AtKit.localisation("tts_rewind"),
'icon': AtKit.getPluginURL() + "images/control-stop-180.png",
'fn': function(){
var scrubAmount = 2;
var currentPosition = AtKit.get("TTS_position");
var newPosition = (currentPosition - scrubAmount);
if(newPosition < 0) newPosition = 0;
var targetObj = ($lib.browser == "msie") ? swfobject.getObjectById(AtKit.get('ATAudioPlayerID')) : window.document['audioe'];
targetObj.sendEvent('seek', newPosition);
}
},
'ttsStop': {
'tooltip': AtKit.localisation("tts_stop"),
'icon': AtKit.getPluginURL() + "images/control-stop-square.png",
'fn': function(){
var targetObj = ($lib.browser == "msie") ? swfobject.getObjectById(AtKit.get('ATAudioPlayerID')) : window.document['audioe'];
targetObj.sendEvent('stop');
AtKit.call('TTSRemoveControlBox');
}
}
}
};*/
// Add functions to AtKit.
AtKit.addFn('getSelectedTextTTS', function(strip){
var text = AtKit.call('getSelectedTextInElement');
if(text == null){
var text = '';
if (document.selection && document.selection.type != "Control" && document.selection.createRange().text != "") {
text = document.selection.createRange().text;
} else if (window.getSelection && window.getSelection().toString() != ""){
text = window.getSelection().toString();
} else if (document.getSelection){
text = document.getSelection();
}
}
if(strip === true){
return String(text).replace(/([\s]+)/ig, '');
} else {
return String(text);
}
});
AtKit.addFn('getSelectedTextInElement', function(){
var e = document.activeElement;
return (
/* mozilla / dom 3.0 */
('selectionStart' in e && function() {
var l = e.selectionEnd - e.selectionStart;
return e.value.substr(e.selectionStart, l);
}) ||
/* exploder */
(document.selection && function() {
var nn = $lib(e).prop('nodeName');
if(nn != "input" && nn != "textarea") return null;
e.focus();
var r = document.selection.createRange();
if (r === null) {
return null;
}
var re = e.createTextRange();
var rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return r.text;
}) ||
/* browser not supported */
function() { return null; }
)();
});
AtKit.addFn('b64', function(input){
// + == _
// / == -
var bkeys = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-=";
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = AtKit.call('utf8_encode', input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
bkeys.charAt(enc1) + bkeys.charAt(enc2) +
bkeys.charAt(enc3) + bkeys.charAt(enc4);
}
return output;
});
AtKit.addFn('utf8_encode', function(string){
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
});
AtKit.addFn('sendTTSChunk', function(args){
if(args.block == 1){
var start = 0;
} else {
var start = (settings.ttsChunkSize * args.block);
}
if( (start + settings.ttsChunkSize) > args.fullData.length ){
var endPoint = args.fullData.length;
} else {
var endPoint = (start + settings.ttsChunkSize);
}
var payload = args.fullData.substring(start, endPoint);
var urlString = settings.speechServicesURL + 'insipio-tts/request.php?rt=tts&v=2&i=1&l=' + AtKit.getLanguage() + '&voice=' + args.voice + '&id=' + args.reqID + '&data=' + payload + "&chunkData=" + args.totalBlocks + "-" + args.block;
if( args.block == args.totalBlocks-1 ){
urlString += "&page=" + encodeURIComponent(window.location);
}
urlString += "&callback=?";
$lib.getJSON(urlString, function(RO){
$lib("#compactStatus").html(args.block + " / " + args.totalBlocks);
var errorTitle = "<h2>" + AtKit.localisation("tts_error") + "</h2>";
if(args.block == args.totalBlocks){
// Finished request..
AtKit.show(TTSDialogs.starting);
if(RO.status == "encoding"){
AtKit.call('countdownTTS', { 'timeLeft':(RO.est_completion / RO.chunks), 'id': RO.ID });
} else if(RO.status == "failure" && RO.reason == "overcapacity"){
AtKit.message(errorTitle + "<p>" + AtKit.localisation("tts_overloaded") + "</p>");
} else if(RO.status == "failure" && RO.message === "") {
AtKit.message(errorTitle + "<p>" + AtKit.localisation("tts_problem") + "</p>");
} else {
AtKit.message(errorTitle + "<p>" + RO.reason + " " + RO.data.message + "</p>");
}
} else {
// Send the next block.
if(RO.data.message == "ChunkSaved"){
AtKit.call('sendTTSChunk', { 'fullData':args.fullData, 'block':(args.block + 1), 'totalBlocks':args.totalBlocks, 'reqID':args.reqID });
} else {
AtKit.message(errorTitle + "<p>" + AtKit.localisation("tts_servererror") + "</p>");
}
}
});
});
AtKit.addFn('countdownTTS', function(arg){
if(isNaN(arg.timeLeft)){
AtKit.message("<h2>" + AtKit.localisation("tts_error") + "</h2> <p>" + AtKit.localisation("tts_problem") + "</p>");
} else {
if(arg.timeLeft == 0){
// Play audio
var audioContainer = "audioo";
if($lib.browser != "msie"){
$lib('body').append( $lib("<div id=\"flashContent\"><OBJECT classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0\" width=\"1\" height=\"1\" id=\"audioe\"> <PARAM name=movie value=\"" + settings.speechServicesURL + "lib/player/player-licensed.swf\"></PARAM> <PARAM name=flashvars value=\"file=" + settings.speechServicesURL + "cache/" + arg.id + ".xml&autostart=true&playlist=bottom&repeat=list&playerready=playerReady&id=" + audioContainer + "\"><PARAM name=allowscriptaccess value=\"always\" /><embed type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" src=\"" + settings.speechServicesURL + "lib/player/player-licensed.swf\" width=\"1\" height=\"1\" allowscriptaccess=\"always\" allowfullscreen=\"false\" flashvars=\"file=" + settings.speechServicesURL + "cache/" + arg.id + ".xml&autostart=true&playlist=bottom&repeat=list&playerready=playerReady\" name=\"audioe\" /> </OBJECT></div>") );
AtKit.call('setupTTSListeners');
} else {
$lib("<div />", {'id': 'flashContent' }).prependTo("body");
var params = {
flashvars: "file=" + settings.speechServicesURL + "cache/" + arg.id + ".xml&autostart=true&playlist=bottom&repeat=list&playerready=playerReady&id=" + audioContainer,
allowscriptaccess: "always"
};
var attributes = {
id: audioContainer,
name: audioContainer
};
swfobject.embedSWF(settings.speechServicesURL + "lib/player/player-licensed.swf", "flashContent", "1", "1", "9.0.0","expressInstall.swf", false, params, attributes, function(){
AtKit.call('setupTTSListeners');
});
}
AtKit.hideDialog();
} else {
$lib('#sbttstimeremaining').html( arg.timeLeft + " " + AtKit.localisation("tts_seconds"));
window.setTimeout(function(){ AtKit.call('countdownTTS', { 'timeLeft':(arg.timeLeft - 1), 'id':arg.id }) }, 1000);
}
}
});
AtKit.addFn('setupTTSListeners', function(args){
if(AtKit.get('TTS_Listeners_setup') == true) return;
window.playerReady = function(obj) {
AtKit.set('ATAudioPlayerID', obj.id);
/*
for(b in TTSExtendedObject.TTSButtons){
var obj = TTSExtendedObject.TTSButtons[b];
AtKit.addButton(b, obj.tooltip, obj.icon, obj.fn);
}*/
// Set values.
AtKit.set("TTS_position", 0);
AtKit.set("TTS_playingItem", 0);
// Add page listeners
var playerObj = swfobject.getObjectById(obj.id);
if($lib.browser != "msie"){
playerObj = window.document["audioe"];
}
playerObj.addModelListener("STATE", "ATBarAudioStateListener");
playerObj.addModelListener("TIME", "ATBarAudioTimeMonitor");
playerObj.addControllerListener("ITEM", "ATBarAudioItemMonitor");
};
window.ATBarAudioTimeMonitor = function(obj){
AtKit.set('TTS_position', obj.position);
}
window.ATBarAudioItemMonitor = function(obj){
AtKit.set('TTS_playingItem', obj.index);
}
window.ATBarAudioStateListener = function(obj) {
var state = obj.newstate;
var playerObj = swfobject.getObjectById(obj.id);
if($lib.browser != "msie"){
playerObj = window.document["audioe"];
}
if(state == "COMPLETED" && (AtKit.get('TTS_playingItem') + 1) == playerObj.getPlaylist().length){
// Completed, remove controlbox and reset everything back to normal.
AtKit.call('TTSRemoveControlBox');
}
if(state == "IDLE" || state == "PAUSED") {
$lib('#at-lnk-ttsPlay').children('img').attr('src', AtKit.getPluginURL() + "images/control.png");
$lib('#at-btn-tts').children('img').attr('src', AtKit.getPluginURL() + "images/sound.png").css('padding-top', '6px');
} else {
if(AtKit.get('TTS_clickEnabled') == false){
$lib('#at-lnk-ttsPlay').children('img').attr('src', AtKit.getPluginURL() + "images/control-pause.png");
$lib('#at-btn-tts').children('img').attr('src', AtKit.getPluginURL() + "images/loading.gif").css('padding-top', '8px');
}
}
}
AtKit.set('TTS_Listeners_setup', true);
});
AtKit.addFn('TTSRemoveControlBox', function(){
AtKit.removeButton('ttsPlay');
AtKit.removeButton('ttsRewind');
AtKit.removeButton('ttsStop');
$lib("#flashContent").remove();
$lib('#at-lnk-tts').children('img').attr('src', AtKit.getPluginURL() + "images/sound.png").css('padding-top', '6px');
AtKit.set('TTS_clickEnabled', true);
});
AtKit.addFn('sbStartTTSSelection', function(args){
AtKit.set('TTS_clickEnabled', false);
var selectedData = AtKit.get('TTSselectedData');
if(selectedData == "" || typeof selectedData == "undefined") selectedData = AtKit.call('getSelectedTextTTS');
if(typeof selectedData != "undefined" && selectedData !== ""){
this.clickEnabled = false;
// Send the data in chunks, as chances are we cant get it all into one request.
var transmitData = AtKit.call('b64', selectedData );
var chunks = Math.ceil(transmitData.length / settings.ttsChunkSize);
if(chunks > 0){
var reqID = Math.floor(Math.random() * 5001);
AtKit.message( "<h2>" + AtKit.localisation("tts_pleasewait") + "</h2><p>" + AtKit.localisation("tts_converting") + "...<br /><div id='compactStatus'>0 / " + chunks + "</div></p>" );
AtKit.call('sendTTSChunk', { 'fullData':transmitData, 'block':1, 'totalBlocks':chunks, 'reqID':reqID, 'voice':args.voice });
} else {
AtKit.message( "<h2>" + AtKit.localisation("tts_error") + "</h2><p>" + AtKit.localisation("tts_problem") + "</p>" );
}
} else {
AtKit.message("<h2>" + AtKit.localisation("tts_title") + "</h2><p>" + AtKit.localisation("tts_explain") + "</p>");
}
});
AtKit.set('TTS_clickEnabled', true);
$lib(document).delegate('#at-btn-tts', 'mousemove, focus, mouseover', function(){
var text = AtKit.call('getSelectedTextTTS');
if(typeof text == "undefined" || text == "") return;
AtKit.set('TTSselectedData', text);
});
AtKit.addButton(
'tts',
AtKit.localisation("tts_title"),
AtKit.getPluginURL() + 'images/sound.png',
function(dialogs, functions){
if(AtKit.set('TTS_clickEnabled') == false) return;
var text = AtKit.call('getSelectedTextTTS');
if(AtKit.get('TTSselectedData') == "" && text != "") AtKit.set('TTSselectedData', text);
AtKit.show(dialogs.options);
AtKit.set('TTS_Listeners_setup', false);
AtKit.addScript(settings.baseURL + 'resources/js/swfobject.js', null);
$lib('#sbStartTTSSelectionMale').click(function(){
AtKit.call('sbStartTTSSelection', { 'voice':'male' });
});
$lib('#sbStartTTSSelectionFemale').click(function(){
AtKit.call('sbStartTTSSelection', { 'voice':'female' });
});
},
TTSDialogs, TTSFunctions//, TTSExtendedObject
);
};
if(typeof window['AtKit'] == "undefined"){
window.AtKitLoaded = function(){
var eventAction = null;
this.subscribe = function(fn) {
eventAction = fn;
};
this.fire = function(sender, eventArgs) {
if (eventAction !== null) {
eventAction(sender, eventArgs);
}
};
};
window['AtKitLoaded'] = new AtKitLoaded();
window['AtKitLoaded'].subscribe(function(){ AtKit.registerPlugin(pluginName, plugin); });
} else {
AtKit.registerPlugin(pluginName, plugin);
}
})();