-
Notifications
You must be signed in to change notification settings - Fork 2
/
textreader-ms.html
1133 lines (1046 loc) · 51.2 KB
/
textreader-ms.html
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Text Reader using Microsoft Azure Text-to-speech</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="./audiobuffer-to-wav.js"></script>
<style type="text/css">
#t {
width: 70%;
height: 300px;
}
</style>
<script type="text/javascript">
const regionPrefix = "YOUR_REGION";
var reqQueue = [];
var audioQueue = [];
var rate = 1;
var playerPointer = -1;
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var abQueue = [];
var token = "";
var tokenTime = 0;
var cheapVoice = "";
var staticAudio = [];
function insertText(str) { //Insert text at the cursor in a textarea
let obj = $("#t").get(0);
if (document.selection) {
var sel = document.selection.createRange();
sel.text = str;
} else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
var startPos = obj.selectionStart,
endPos = obj.selectionEnd,
cursorPos = startPos,
tmpStr = obj.value;
obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
cursorPos += str.length;
obj.selectionStart = obj.selectionEnd = cursorPos;
} else {
obj.value += str;
}
$("#t").focus();
}
function wrapText(openTag, closeTag) {
var textArea = $('#t');
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
$("#t").focus();
}
function insertTxt(text, index, insert) {
let start = text.substring(0, index);
let end = text.substring(index);
return (start + insert + end);
}
function sleep(interval) {
return new Promise(resolve => {
setTimeout(resolve, interval);
})
}
function previewPlay(src) {
let p = $("#previewer")[0];
if (p.currentSrc != src) {
p.src = src;
p.play();
} else {
p.pause();
}
}
async function getToken() {
console.log("Obtaining token...");
let retryTimes = 3;
let i;
for (i = 0; i < retryTimes; i++) {
await fetch("https://" + regionPrefix + ".api.cognitive.microsoft.com/sts/v1.0/issuetoken", {
method: "POST",
headers: {
"Ocp-Apim-Subscription-Key": "YOUR_SUBSCRIPTION_KEY",
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(res => {
if (!res.ok) {
i = 90;
throw new Error(res.statusText);
} else {
i = 99;
return res.text();
}
}).then(restext => {
if (restext != "") {
token = restext;
console.log("Token retrieved. ");
tokenTime = new Date().getTime();
}
}).catch(reason => {
console.log("Failed to get token." + reason);
if (i != 90 && i < retryTimes - 1) console.log("Retrying...");
});
await sleep(3000);
}
if (i < 99) {
alert("Failed to obtain token.");
return false;
} else {
return true;
}
}
async function checkToken() {
if (new Date().getTime() - tokenTime > 540000) {
console.log("Token expired. Re-retrieving...");
await getToken();
}
}
function process(pre) {
console.log("Start processing input... -->");
var defaultVoice = $("body > #voice").val();
var text = $("#t").val()
var paras = [];
rate = $("#speed").val();
if (text.indexOf("<audio id=") != -1) {
let findAudio = new RegExp(/<audio id="([0-9]+)"/gmi);
let result;
while ((result = findAudio.exec(text)) != null) {
if (staticAudio[Number(result[1])] == undefined) {
return false;
}
}
}
if (text.indexOf("<repeat ") != -1) {
let findRepeat = new RegExp(/<repeat count='([\s\S]*?)'>([\s\S]*?)<\/repeat>/gmi);
let result;
let prevLastIndex = 0;
while ((result = findRepeat.exec(text)) != null) {
if (prevLastIndex != result.index) paras.push(text.substring(prevLastIndex, result.index));
if (result[2].length > 200) {
for (let index = 0; index < Number(result[1]); index++) { //repeat the content in a very "direct" way ;-)
paras.push(result[2]);
}
} else {
let thistext = "";
for (let index = 0; index < Number(result[1]); index++) thistext += result[2];
paras.push(thistext);
}
prevLastIndex = findRepeat.lastIndex;
}
if (prevLastIndex != text.length) paras.push(text.substr(prevLastIndex));
} else {
paras.push(text);
}
for (let i = 0; i < paras.length; i++) {
paras[i] = paras[i].trim();
if (paras[i] != "") //not blank
{
if (defaultVoice.indexOf("zh-CN") == -1) {
let findChinese = new RegExp(/(([^"][0-9(“《\u4E00-\u9FA5\uFE30-\uFFA0]+[(“《\u4E00-\u9FA5\uFE30-\uFFA0]+[0-9(“《\u4E00-\u9FA5\uFE30-\uFFA0]+[,。?!”…》)\n]*)+)/gim);
while (findChinese.exec(paras[i]) != null) {
paras[i] = paras[i].replace(findChinese, "<voice name='" + $("#zh_CN > option:nth-child(1)").val() + "'>$1</voice>");
break;
}
let findDuplicate = new RegExp(/(<voice name=[\s\S]*?>)([0-9\., \u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b]*?)(<voice name=[\s\S]*?>)(([\u4E00-\u9FA5]|[\uFE30-\uFFA0])+)<\/voice>([0-9\., \u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b]*?)<\/voice>/gim);
paras[i] = paras[i].replace(findDuplicate, "$1$2$4$6</voice>");
}
}
}
for (let i = 0; i < paras.length; i++) {
if (paras[i] != "") //not blank
{
let findBreak = new RegExp(/(<break [\s\S]*?\/>)/gim);
while (findBreak.exec(paras[i]) != null) {
paras[i] = paras[i].replace(findBreak, "<voice name='" + cheapVoice + "'>$1</voice>");
break;
}
}
}
paras.forEach((element, index) => {
if (element != "") {
element = element.replace(/<voice/gm, "<a");
element = element.replace(/<\/voice>/gm, "</a>");
let thistext = "<html><body><div>" + element + "</div></body></html>", xmlDoc = $.parseHTML(thistext), $xml = $(xmlDoc);
$xml.contents().filter(function () { return this.nodeType == 3 || (this.nodeName.toLowerCase() != "a" && this.nodeName.toLowerCase() != "audio"); }).wrap('<a name=\"' + defaultVoice + '\"></a>');
let tmpStr = $xml.html();
tmpStr = tmpStr.replace(/<a name="[A-z\- ]*?">([\s]*?)<\/a>/gm, "$1");
tmpStr = tmpStr.replace(/<a /gm, "<voice ");
tmpStr = tmpStr.replace(/<\/a>/gm, "</voice>");
paras[index] = tmpStr;
}
});
for (let index = 0; index < paras.length; index++) {
const element = paras[index];
const $xml = $("<xml>" + element + "</xml>");
do {
var letscont = false;
$xml.find("voice").each(function () {
if ($(this).attr("name") == $(this).next().attr("name")) {
$(this).append($(this).next().html());
$(this).next().remove();
letscont = true;
}
});
} while (letscont);
paras[index] = $xml.html();
}
if (pre != undefined) //For the express-as tag
{
return paras;
}
if (text.indexOf("<audio src=") != -1 || text.indexOf("<audio id=") != -1) {
paras.forEach((element, index) => {
element = element.replace(/"><\/audio>/gmi, "\"/>");
let findAudio = new RegExp(/<audio ((src="[\s\S]+"[ ]*?)|(id="[0-9]+"[ ]*?)|(id="[0-9]+"[ ]*? name="([\S ][^\/"]+)"))\/>/gmi);
let result, insertCount = 0, tmpStr = element;
while ((result = findAudio.exec(element)) != null) {
tmpStr = insertTxt(tmpStr, result.index + insertCount * ("||".length), "||");
insertCount++;
tmpStr = insertTxt(tmpStr, findAudio.lastIndex + insertCount * ("||".length), "||");
insertCount++;
}
tmpStr = tmpStr.replace(/\|\|([\s]+)\|\|/gm, "$1||");
let tmpPara = tmpStr.split("||");
tmpPara.unshift(index, 1);
Array.prototype.splice.apply(paras, tmpPara);
});
}
paras.forEach((element, index) => {
let findVoicetag = new RegExp(/<\/voice>/gmi);
let result, lastIndexes = [];
while ((result = findVoicetag.exec(element)) != null) {
lastIndexes.push(findVoicetag.lastIndex);
}
if (lastIndexes.length > 5) //MS allows only 5 <voice> tags inside a request
{
for (let i = 1; i < Math.ceil(lastIndexes.length / 5); i++) {
element = insertTxt(element, lastIndexes[i * 5 - 1] + (i - 1) * ("||".length), "||");
}
let tmpPara = element.split("||");
tmpPara.unshift(index, 1);
Array.prototype.splice.apply(paras, tmpPara);
}
});
for (let index = 0; index < paras.length; index++) {
if (paras[index] != "") {
let findEndofSent = new RegExp(/(: |\. |\? |! |\.\"|\?\"|!\"|:|。|?|!|。”|?”|!”|……)/gm);
let result;
let prevLastIndex = [0];
if (paras[index].length > 780) { //MS allows only 1000 chars in a request, with <speak...> counts up to 200 chars
while ((result = findEndofSent.exec(paras[index])) != null) {
prevLastIndex.push(findEndofSent.lastIndex);
}
let lastOffset = 0;
let subparaCount = 1;
for (let j = 0; j < prevLastIndex.length; j++) {
if (prevLastIndex[j] - lastOffset > 780) {
paras.splice(index + subparaCount, 0, paras[index].substring(lastOffset, prevLastIndex[j - 1]));
lastOffset = prevLastIndex[j - 1];
subparaCount++;
j--;
}
}
if (prevLastIndex.indexOf(lastOffset) < prevLastIndex.length - 1) {
paras.splice(index + subparaCount, 0, paras[index].substring(lastOffset));
}
paras.splice(index, 1);
}
}
}
let startofTags = [];
let startofTagsName = [];
let startofTagsIndex = [];
for (let i = 0; i < paras.length; i++) {
if (paras[i] != "") {
let findStartofTag = new RegExp(/<(voice|prosody|mstts:express-as|p|s|phoneme|say-as|mstts:backgroundaudio)[\s\S]*?>/gmi);
let result;
while ((result = findStartofTag.exec(paras[i])) != null) {
startofTags.push(result[0]);
startofTagsName.push(result[1]);
startofTagsIndex.push(result.index);
}
if (startofTags.length > 0) {
if (paras[i].search(findStartofTag) != -1) {
for (let j = startofTags.length - 1; j >= 0; j--) {
if (paras[i].indexOf("</" + startofTagsName[j] + ">", startofTagsIndex[j]) != -1) //This tag is closed.
{
startofTagsName.splice(j, 1);
startofTags.splice(j, 1);
startofTagsIndex.splice(j, 1);
}
}
for (let j = startofTags.length - 1; j >= 0; j--) {
let tmpStr = paras[i].indexOf("<" + startofTagsName[j]) == -1 ? paras[i] : paras[i].substring(0, paras[i].indexOf("<" + startofTagsName[j]));
if (tmpStr.indexOf("</" + startofTagsName[j] + ">") != -1 && tmpStr.indexOf(startofTags[j]) == -1) { //Found the close tag of a tag started in prev para.
paras[i] = startofTags[j] + paras[i];
startofTagsName.splice(j, 1);
startofTags.splice(j, 1);
startofTagsIndex.splice(j, 1);
continue;
}
if (paras[i].indexOf("</" + startofTagsName[j] + ">", startofTagsIndex[j]) == -1) { //This tag is not closed. Add a temporal close tag.
paras[i] += "</" + startofTagsName[j] + ">";
}
}
} else { //No start of tags found in this para
if (paras[i].search(/<\/[\S]*?>/) != -1) {
for (let j = startofTags.length - 1; j >= 0; j--) {
if (paras[i].indexOf("</" + startofTagsName[j] + ">") != -1) {
paras[i] = startofTags[j] + paras[i];
startofTagsName.splice(j, 1);
startofTags.splice(j, 1);
startofTagsIndex.splice(j, 1);
}
}
} else {
if (startofTags.length > 0) {
for (let j = startofTags.length - 1; j >= 0; j--) {
paras[i] = startofTags[j] + paras[i] + "</" + startofTagsName[j] + ">";
}
}
}
}
}
}
}
paras.forEach(element => {
if (element.trim() != "") {
if (element.indexOf("mstts") == -1) {
reqQueue.push("<speak version=\"1.0\" xmlns=\"https://www.w3.org/2001/10/synthesis\" xml:lang=\"en-US\">" + element + "</speak>");
} else {
reqQueue.push("<speak version=\"1.0\" xmlns=\"https://www.w3.org/2001/10/synthesis\" xmlns:mstts=\"https://www.w3.org/2001/mstts\" xml:lang=\"en-US\">" + element + "</speak>");
}
}
});
console.log("Now reqQueue looks like:" + reqQueue.join("||"));
console.log("<-- Process complete.");
return true;
}
function optimizeReq() {
reqQueue.forEach((element, index) => {
reqQueue[index] = element.replace(/&/gm, " and ");
reqQueue[index] = element.replace(/</gm, "<");
reqQueue[index] = element.replace(/>/gm, ">");
reqQueue[index] = element.replace(/'/gm, "'");
reqQueue[index] = element.replace(/"/gm, """);
reqQueue[index] = element.replace(/ /gm, " ");
});
for (let index = 0; index < reqQueue.length; index++) {
if (reqQueue[index].trim() == "") {
reqQueue.splice(index, 1);
index--;
}
}
for (let i = 0; i < reqQueue.length; i++) { //Rewrite JSON to reuse audio
if (reqQueue[i].indexOf("<speak") != -1) {
for (let j = 0; j < reqQueue.length; j++) {
if (reqQueue[i] == reqQueue[j] && i > j) {
reqQueue[i] = "{ \"repeatLine\" : \"" + j + "\" }";
}
}
}
}
console.log("reqQueue optimized. Now JSON queue looks like: " + reqQueue);
}
async function sendReq() {
if (reqQueue.length > 0) {
console.log("Sending requests to the server.");
for (let i = 0; i < reqQueue.length; i++) {
console.log("Requesting line " + i + "...");
if (reqQueue[i].indexOf("<audio src=") != -1) {
let findAudio = new RegExp(/<audio src="([\S]+)"\/>/gmi);
let result = findAudio.exec(reqQueue[i]);
console.log("Loading external audio file: " + result[1]);
await fetch(result[1]).then(res => {
if (res.ok) {
return res.blob();
} else {
throw new Error(res.statusText);
}
}).then(resblob => {
if (resblob != undefined) {
console.log("Audio #" + i + " received.");
audioQueue.push(URL.createObjectURL(resblob));
}
}).catch(reason => {
console.log("Unable to load audio file: " + result[1] + ", " + reason);
});
} else if (reqQueue[i].indexOf("<audio id=") != -1) {
let findAudio = new RegExp(/<audio id="([0-9]+)"[\S ]*?( name="([\S ][^\/"]+)")?\/>/gmi);
let result = findAudio.exec(reqQueue[i]);
console.log("Loading staticAudio #" + result[1]);
let targetAudio = staticAudio[Number(result[1])];
if (targetAudio == undefined) {
audioQueue.push("");
} else {
audioQueue.push(targetAudio);
}
} else if (reqQueue[i].indexOf("\"repeatLine\"") != -1) { //Reuse audio for same content
let thisjson = JSON.parse(reqQueue[i]);
audioQueue.push(audioQueue[Number(thisjson.repeatLine)]);
console.log("Reusing audio #" + thisjson.repeatLine + " for JSON #" + i);
} else {
let retryTimes = 3;
let index;
for (index = 0; index < retryTimes; index++) {
await fetch("https://" + regionPrefix + ".tts.speech.microsoft.com/cognitiveservices/v1", {
method: 'POST',
headers: {
'X-Microsoft-OutputFormat': 'audio-24khz-160kbitrate-mono-mp3',
'Content-Type': 'application/ssml+xml',
'Authorization': 'Bearer ' + token
},
body: reqQueue[i]
}).then(res => {
if (res.ok) {
index = 99;
return res.blob();
} else {
index = 90;
throw new Error(res.statusText);
}
}).then(resblob => {
if (resblob != undefined) {
console.log("Audio #" + i + " received.");
audioQueue.push(URL.createObjectURL(resblob));
}
}).catch(reason => {
console.log("Failed to retrieve audio #" + i + ": " + reason + ".");
if (index != 90 && index < retryTimes - 1) console.log("Retrying...");
});
await sleep(3000);
}
if (index < 99) {
console.error("Failed to retrieve audio #" + i);
}
}
}
if (audioQueue.length != reqQueue.length) {
alert("Some lines are not synthesized correctly.");
} else {
console.log("All audio has been retrieved.");
}
$("#saveit").removeAttr("disabled"); //saveit button state change
} else {
alert("Type in something first!");
}
}
async function getVoices() {
console.log("Requesting voice list...");
let retryTimes = 3;
let index;
for (index = 0; index < retryTimes; index++) {
await fetch("https://" + regionPrefix + ".tts.speech.microsoft.com/cognitiveservices/voices/list", {
method: 'GET',
headers: {
"Authorization": "Bearer " + token
}
}).then(res => {
if (!res.ok) {
index = 90;
throw new Error(res.statusText);
} else {
index = 99;
return res.json();
}
}).then(resjson => {
console.log("Voice list received. ");
for (const key in resjson) {
if (resjson[key].Locale.indexOf("en-US") != -1) {
if (resjson[key].VoiceType == "Neural") {
$("#en_US").append("<option value='" + resjson[key].ShortName + "'>(" + resjson[key].Gender + ") " + resjson[key].ShortName.replace(/(en-US-)([\s\S]*?)(Neural)/, "$2") + " </option>");
} else {
cheapVoice = resjson[key].ShortName;
}
} else if (resjson[key].Locale.indexOf("zh-CN") != -1) {
if (resjson[key].VoiceType == "Neural") {
$("#zh_CN").append("<option value='" + resjson[key].ShortName + "'>(" + resjson[key].Gender + ") " + resjson[key].ShortName.replace(/(zh-CN-)([\s\S]*?)(Neural)/, "$2") + " </option>");
}
}
}
//Submit button state change
$("#sub").removeAttr("disabled");
}).catch(reason => {
console.log("Failed to get voice list. " + reason);
if (index != 90 && index < retryTimes - 1) console.log("Retrying...");
});
await sleep(3000);
}
if (index < 99) alert("Failed to retrieve voice list.");
}
async function joinAudio() {
var ttlLength = 0;
var sr;
if (audioQueue.length <= 0) {
alert("Speak it at least once first!");
reject("No audio received yet.");
} else {
console.log("Begin Join Audio -->");
for (let i = 0; i < audioQueue.length; i++) {
console.log("Process Audio #" + i);
await fetch(audioQueue[i]).then(function (response) {
if (!response.ok) {
throw new Error('HTTP error, status = ' + response.status);
} else {
return response.arrayBuffer();
}
}).then(async function (response) {
await audioCtx.decodeAudioData(response).then(function (buffer) {
var b = buffer.getChannelData(0);
//console.log (b.numberOfChannels);
abQueue.push(b);
ttlLength += b.length;
sr = buffer.sampleRate;
});
});
}
console.log("Total length: " + ttlLength);
let resultBuffer = audioCtx.createBuffer(1, ttlLength, sr);
let rbData = resultBuffer.getChannelData(0);
var j = 0;
for (let i = 0; i < abQueue.length; i++) {
await rbData.set(abQueue[i], j);
j += abQueue[i].length;
}
console.log("<-- End of Join Audio");
return resultBuffer;
}
}
async function saveAudio() {
if (audioQueue.length <= 0) {
alert("Speak it at least once first!");
} else {
try {
await joinAudio().then(function (b) {
console.log(b);
let wav = audioBufferToWav(b);
var blob = new Blob([new DataView(wav)], {
type: "audio/wav"
});
console.log(blob);
console.log("Triggering download...");
let a = document.createElement('a');
a.download = new Date().getTime().toString() + '.wav';
let dl = window.URL.createObjectURL(blob);
a.href = dl;
$("body").append(a);
a.click();
$(a).remove();
URL.revokeObjectURL(dl);
});
} catch (error) {
alert("An error occured when exporting the audio: " + error);
} finally {
$("#saveit").removeAttr("disabled"); //saveit button state change
}
}
}
</script>
</head>
<body>
<h1>Text Reader using Microsoft Azure Text-to-speech</h1><br>
Default voice: <select id="voice">
<optgroup label="US English" id="en_US">
</optgroup>
<optgroup label="Mandarin Chinese" id="zh_CN">
</optgroup>
</select>
<div style="display: none;"> Rate: <input type="range" id="speed" min="0.25" max="4.0" step="0.01">
<input type="text" id="speedtxt"></div>
<br>
<button id="insertAudio">Insert audio file</button> <button id="supplyMissingAudio" style="display: none;">Supply
missing audio files</button> <button id="insertPause">Insert Pause</button>
<div id="showOnSelect"><button id="insertRepeat">Insert repeat</button> <button id="changevoice">Change
voice</button>
<button id="dlgmaker">Dialog Maker</button> <!-- <button id="insertEmph">Insert emphasis</button> --> <button
id="insertProsody">Insert prosody</button> <button id="insertExpressAs">Adjust speaking styles</button>
</div> <br>
<textarea id="t" autofocus required spellcheck="false" placeholder="Enter text you wish spoken here."></textarea>
<br>
<button id="sub">Speak it!</button> <button id="saveit">Save audio to file</button>
<br>
<div id="choosevoicedlg" style="display: none;"><b>Choose a voice: </b>
<div id="dlgvoicelist0"></div> <button id="dlgok0">OK</button> <button id="dlgcancel0">Cancel</button>
</div>
<div id="dlgmakerdlg" style="display: none;">Choose a voice for each character: <br>
<div id="charlist"></div><button id="dlgok1">OK</button> <button id="dlgcancel1">Cancel</button>
</div>
<div id="emphasisdlg" style="display: none;">Choose an emphasis level: <select id="emphlvl">
<option value="strong">Strong</option>
<option value="moderate">Moderate</option>
<option value="none" selected>None</option>
<option value="reduced">Reduced</option>
</select><br><button id="dlgok2">OK</button> <button id="dlgcancel2">Cancel</button></div>
<div id="prosodydlg" style="display: none;">Set prosody:<br>Pitch:<input type="range" id="pitch" min="-8" max="8"
value="0"> <input type="number" id="pitchtxt" max="8" min="-8" step="1">semitone <br> Rate: <input
type="range" id="rate" min="0.5" max="5" value="1" step="0.01"> <input type="number" id="ratetxt" min="0.5"
max="5" step="0.01" value="1"><br><button id="dlgok3">OK</button> <button id="dlgcancel3">Cancel</button>
</div>
<div id="expressdlg" style="display: none;">Adjust speaking styles: <br /><select id="expressstyle-j"
style="display: none;">
<option value="cheerful">Cheerful</option>
<option value="empathy">Empathy</option>
<option value="chat">Chat</option>
<option value="newscast">News Cast</option>
<option value="customerservice">Customer Service</option>
</select>
<select id="expressstyle-x" style="display: none;">
<option value="newscast">Newscast</option>
<option value="sentiment">Sentiment</option>
</select><br><button id="dlgok4">OK</button> <button id="dlgcancel4">Cancel</button>
</div>
<div id="insertaudiofiledlg" style="display: none;">Insert audio file:
<br /> <audio id="previewer" style="display: none;"></audio>
<div id="audiolist">
<p class="filebrowser"><label> <input type="radio" name="a" id="audios" value="-1" checked> Pick a file:
<input type="file" id="audiofile" accept="audio/*"></label></p>
<label> <input type="radio" name="a" id="audios" value="-2"><input type="url" id="audiourl"
placeholder="Enter URL to the audio file. e.g.: http://example.com/a.mp3" size="80"> </label><br />
</div>
<br><button id="dlgok5">OK</button> <button id="dlgcancel5">Cancel</button>
</div>
<div id="missingaudiodlg" style="display: none;">Missing audio files: <br />Please supply the missing audio
files:<br />
<div id="missingaudiolist"></div>
<br /> <button id="dlgok6">OK</button>
</div>
<script type="text/javascript">
$(document).ready(function () {
getToken().then(ok => {
if (ok) getVoices();
}).catch(e => { });
//Submit button state change
$("#sub").attr("disabled", "true");
$("#sub").click(function () {
if ($("#t").val().length <= 0) {
alert("Type in something first!");
return;
}
if (audioQueue.length <= 0) {
//Submit button state change
$("#sub").attr("disabled", "true");
$("#sub").text("Please wait...");
if (!process()) {
alert("Some audio files are missing. Please supply them and try again.");
$("#supplyMissingAudio").click();
//Submit button state change
$("#sub").removeAttr("disabled");
$("#sub").text("Speak it!");
} else {
optimizeReq();
checkToken().then(() => {
sendReq();
});
}
} else {
if (player.ended && playerPointer >= audioQueue.length - 1) {
console.log("Audio already retrieved. Start playing.");
playerPointer = -1;
// Play audioQueue directly.
//Submit button state change
$("#sub").text("Pause");
} else {
if (!player.ended && player.paused) {
player.play();
//Submit button state change
$("#sub").text("Pause");
} else if (!player.ended && !player.paused) {
player.pause();
//Submit button state change
$("#sub").text("Resume");
}
}
}
});
$("#speed").val("1.0");
$("#showOnSelect").css("display", "none");
const player = new Audio();
player.loop = false;
player.addEventListener("ended", () => {
if (playerPointer >= audioQueue.length - 1) {
if (audioQueue.length > 0) {
//Submit button state change
$("#sub").text("Replay");
} else {
//Submit button state change
$("#sub").text("Speak it!");
}
}
});
var docWatch = setInterval(function () {
if (audioQueue.length > 0 && playerPointer < audioQueue.length - 1) //To make the audio start playing, audioQueue has to have sth, and playerPointer is -1.
{
if (player.ended || (!player.ended && playerPointer == -1)) {
playerPointer++;
player.src = audioQueue[playerPointer];
console.log("Playing Audio #" + playerPointer);
player.play();
//Submit button state change
$("#sub").removeAttr("disabled");
$("#sub").text("Pause");
}
}
if (document.activeElement.id != "speedtxt") {
$("#speedtxt").val($("#speed").val());
}
if (document.activeElement.id != "ratetxt") { //for the prosody dlg
$("#ratetxt").val($("#rate").val());
}
if (document.activeElement.id != "pitchtxt") { //for the prosody dlg
$("#pitchtxt").val($("#pitch").val());
}
if ($("#t")[0].selectionStart != $("#t").get(0).selectionEnd) {
$("#showOnSelect").css("display", "inline");
} else {
$("#showOnSelect").css("display", "none");
}
}, 100);
});
$("#saveit").attr("disabled", "true"); //saveit button state change
$("#saveit").click(() => {
if (reqQueue.length <= 0) {
alert("Type in something and speak it first!");
} else {
if (audioQueue.length < reqQueue.length) {
alert("Please wait until all audio are retrieved.");
} else {
$("#saveit").attr("disabled", "true"); //saveit button state change
saveAudio();
}
}
});
$("#t").change(function () {
reqQueue = [];
audioQueue = [];
playerPointer = -1;
abQueue = [];
//Submit button state change
$("#sub").text("Speak it!");
$("#saveit").attr("disabled", "true"); //saveit button state change
try { player.pause(); } catch (e) { }
});
$("#t").bind("input", () => $("#t").change());
$("#voice").change(function () {
$("#t").change();
});
$("#speedtxt").change(function () {
$("#speed").val($("#speedtxt").val());
$("#t").change();
});
$("#speed").change(function () {
$("#t").change();
})
$("#ratetxt").change(function () { //for the prosody dlg
$("#rate").val($("#ratetxt").val());
});
$("#pitchtxt").change(function () { //for the prosody dlg
$("#pitch").val($("#pitchtxt").val());
});
$("#insertPause").click(() => {
let pause = window.prompt("Pause for how long?" + "\n" + "e.g.:2s", "2s");
if (pause != "" && pause != null) {
if (pause.substr(pause.length - 1, 1) != "s") pause += "s";
if (/([0-9]+)(ms|s)/.test(pause)) {
insertText("<break time=\"" + pause + "\" />");
} else {
alert("Invalid input.");
}
}
});
$("#insertRepeat").click(() => {
let count = window.prompt("Repeat how many times?", "2");
if (count != "" && count != null) {
if (Number(count) == NaN) {
alert("Invalid input.");
} else {
wrapText("<repeat count='" + count + "'>", "</repeat>");
}
}
});
$("#changevoice").click(() => {
if ($("#dlgvoicelist0 > #voice").val() == undefined) {
$("#dlgvoicelist0").append($("body > #voice").clone());
}
$("#choosevoicedlg").css("display", "inline");
});
$("#dlgok0").click(() => {
let v = $("#dlgvoicelist0 > #voice").val();
wrapText("<voice name=\"" + v + "\">", "</voice>");
$("#choosevoicedlg").css("display", "none");
});
$("#dlgcancel0").click(() => {
$("#choosevoicedlg").css("display", "none");
});
$("#dlgmaker").click(() => {
let t = $("#t");
let tt = t.val();
let st = tt.substring(t.get(0).selectionStart, t.get(0).selectionEnd);
let stpara = st.split("\n");
let chara = [];
if (stpara.length < 2) {
alert("I cannot make a conversation out of less than 2 lines.");
} else {
let goahead = true;
for (let i = 0; i < stpara.length; i++) {
if (stpara[i].trim() == "") continue;
let curCharPos = stpara[i].search(/(:|:)/);
if (curCharPos == -1) {
alert("Line " + i + " does not contain a speaker indicator.");
goahead = false;
break;
} else {
let curChar = stpara[i].substring(0, curCharPos);
if (chara.join().indexOf(curChar) == -1) {
chara.push(curChar);
}
}
}
console.log("DialogMaker: Found characters: " + chara);
if (goahead) {
for (let i = 0; i < chara.length; i++) {
$("#charlist").append("<p>" + chara[i] + " —— ");
$("#charlist").append($("body > #voice").clone());
$("#charlist").append("</p>");
}
$("#dlgmakerdlg").css("display", "inline");
}
}
});
$("#dlgok1").click(() => {
let t = $("#t");
let tt = t.val();
let st = tt.substring(t.get(0).selectionStart, t.get(0).selectionEnd);
let stpara = st.split("\n");
let chara = [];
let voices = [];
if (stpara.length < 2) {
alert("I cannot make a conversation out of less than 2 lines.");
} else {
let goahead = true;
for (let i = 0; i < stpara.length; i++) {
if (stpara[i].trim() == "") continue;
if (stpara[i].search(/(:|:)/) == -1) {
alert("Line " + i + " does not contain a speaker indicator.");
goahead = false;
break;
} else {
chara.push(stpara[i].substring(0, stpara[i].search(/(:|:)/) + 1));
}
}
if (goahead) {
for (let i = 0; i < chara.length; i++) {
$("#charlist > #voice").each(function () {
voices.push($(this).val());
});
}
console.log("DialogMaker: Selected voices: " + voices);
for (let i = 0; i < stpara.length; i++) {
for (let j = 0; j < chara.length; j++) {
if (stpara[i].substring(0, stpara[i].search(/(:|:)/) + 1) == chara[j]) {
stpara[i] = stpara[i].replace(chara[j], "<voice name=\"" + voices[j] + "\">");
stpara[i] += " </voice>";
break;
}
}
}
console.log("DialogMaker: Paragraph processed: " + stpara);
st = stpara.join("\n");
$("#t").val(tt.substring(0, t.get(0).selectionStart) + st + tt.substring(t.get(0)
.selectionEnd));
}
}
$("#dlgcancel1").click();
});
$("#dlgcancel1").click(() => {
$("#dlgmakerdlg").css("display", "none");
$("#charlist").empty();
});
$("#insertEmph").click(() => {
$("#emphasisdlg").css("display", "inline");
});
$("#dlgok2").click(() => {
let emph = $("#emphlvl").val();
let t = $("#t");
let tt = t.val();
let st = tt.substring(t.get(0).selectionStart, t.get(0).selectionEnd);
if (st.indexOf("\n") != -1) {
alert("Please don't wrap multiple lines with the <emphasis> tag.");
} else {
wrapText("<emphasis level='" + emph + "'>", "</emphasis>");
}
$("#emphasisdlg").css("display", "none");
});
$("#dlgcancel2").click(() => {
$("#emphasisdlg").css("display", "none");
});
$("#insertProsody").click(() => {
let t = $("#t");
let tt = t.val();
let st = tt.substring(t.get(0).selectionStart, t.get(0).selectionEnd);
if (st.indexOf("</voice>") != -1 || st.indexOf("<voice ") != -1) {
alert("Please don't insert tags across the border of a <voice> tag.");
} else {
$("#prosodydlg").css("display", "inline");
}
});
$("#dlgok3").click(() => {
let rate = $("#rate").val();
let pitch = $("#pitch").val();
let tmpStr = "";
if (Number(rate) != 1) tmpStr += " rate=\"" + rate + "\"";
if (Number(pitch) != 0) tmpStr += " pitch=\"" + (Number(pitch) > 0 ? "\+" + pitch : pitch) + "st\"";
wrapText("<prosody" + tmpStr + ">", "</prosody>");
$("#dlgcancel3").click();
});
$("#dlgcancel3").click(() => {
$("#prosodydlg").css("display", "none");
$("#rate").val("100");
$("#pitch").val("0");
});
$("#insertExpressAs").click(() => {
let t = $("#t");