-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtoneprot.js
1248 lines (1112 loc) · 42.6 KB
/
toneprot.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
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
/*
* SpeakGoodChinese 3
* Copyright (C) 2016 R.J.J.H. van Son (r.j.j.h.vanson@gmail.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You can find a copy of the GNU General Public License at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/
/*
* Global variables from audioProcessing.js
*
* var recordedBlob, recordedBlobURL;
* var recordedArray, currentAudioWindow;
* var recordedSampleRate, recordedDuration;
*
*/
var performanceRecord = {};
var recordPerformance = true;
var setDrawingParam = function (canvasId) {
var drawingArea = document.getElementById(canvasId);
var drawingCtx = drawingArea.getContext("2d");
return drawingCtx;
};
var initializeDrawingParam = function (canvasId) {
var drawingArea = document.getElementById(canvasId);
var drawingCtx = drawingArea.getContext("2d");
resetDrawingParam(drawingCtx);
return drawingCtx;
};
var resetDrawingParam = function (drawingCtx) {
drawingCtx.clearRect(0, 0, drawingCtx.canvas.width, drawingCtx.canvas.height);
drawingCtx.lineWidth = 8;
drawingCtx.strokeStyle = "green";
drawingCtx.lineCap = "round";
drawingCtx.lineJoin = "round";
};
var testDrawing = function (canvasId, color, order) {
var drawingCtx = setDrawingParam(canvasId)
drawingCtx.beginPath();
drawingCtx.strokeStyle = color;
drawingCtx.moveTo(250 + order,250);
drawingCtx.lineTo(750 - order,750);
drawingCtx.stroke();
};
// Handle tone examples
function getTones (pinyin) {
var tones = pinyin.replace(/[^\d]+(\d)/g, "$1");
return Number(tones);
};
function numSyllables (pinyin) {
var tones = pinyin.replace(/[^\d]+(\d)/g, "$1");
return tones.length;
};
function convertVoicing (pinyin) {
var voicing = pinyin.replace(/(ng|[wrlmny])/g, "C");
voicing = voicing.replace(/(sh|ch|zh|[fsxhktpgqdbzcj])/g, "U");
voicing = voicing.replace(/[^CU0-9]/g, "V");
return voicing;
};
// Global constants
//
toneRules_absoluteMinimum = 80
// Movements
var toneRules_range_Factor = 1;
// start * ?Semit is a fall
// start / ?Semit is a rise
// 1/(12 semitones)
var toneRules_octave = 0.5;
// 1/(9 semitones)
var toneRules_nineSemit = 0.594603557501361;
// 1/(6 semitones)
var toneRules_sixSemit = 0.707106781186547;
// 1/(3 semitones) down
var toneRules_threeSemit = 0.840896415253715;
// 1/(2 semitones) down
var toneRules_twoSemit = 0.890898718140339;
// 1/(1 semitones) down
var toneRules_oneSemit = 0.943874313;
// 1/(4 semitones) down
var toneRules_fourSemit = toneRules_twoSemit * toneRules_twoSemit;
// 1/(5 semitones) down
var toneRules_fiveSemit = toneRules_threeSemit * toneRules_twoSemit;
var toneScript_delta = 0.00001;
var toneScript_segmentDuration = 0.150;
var toneScript_fixedDuration = 0.12;
var toneScript_margin = 0.25
var dx = 0.01;
/*
* Tone Duration factor
* Tone 1: D 1
* Tone 2: D 0.8
* Tone 3: D 1.1
* Tone 4: D 0.8
* Tone 0: D 0.5
*
* Durations must be scaled
* Returns the factor with which the duration must be scaled
*
*/
// Procedure to scale the duration of the current syllable
function toneDuration (prevTone, currentTone, nextTone) {
var toneFactor = 1;
if(currentTone == 0) {
var zeroToneFactor;
zeroToneFactor = 0.5
if (prevTone == 2) {
zeroToneFactor = 0.8 * zeroToneFactor
} else if (prevTone == 3) {
zeroToneFactor = 1.1 * zeroToneFactor
} else if (prevTone == 4) {
zeroToneFactor = 0.8 * zeroToneFactor
}
toneFactor = zeroToneFactor * toneFactor
} else if (currentTone == 2) {
toneFactor = 0.8
} else if (currentTone == 3) {
toneFactor = 1.1
} else if (currentTone == 4) {
toneFactor == 0.8
}
// Next tone 0, then lengthen first syllable
if (nextTone == 0) {
toneFactor = toneFactor * 1.2
};
return toneFactor;
}
// The rules to create pitch tracks from tones
function toneRules (topLine, time, lastFrequency, voicedDuration, prevTone, currentTone, nextTone, toneRange) {
if (!toneRange || toneRange <= 0) toneRange = 1;
var syllableToneContour = [];
var durationFactor = toneDuration (prevTone, currentTone, nextTone);
var frequencyRange = toneRules_octave * toneRange;
if(toneRules_range_Factor > 0) {
frequencyRange = frequencyRange * toneRules_range_Factor;
}
//
// Tone toneRules_levels 1-5
// Defined relative to the topline and the frequency range
var toneRules_levelFive = topLine;
var toneRules_levelOne = topLine * frequencyRange;
var toneRules_levelThree = topLine * Math.sqrt(frequencyRange);
var toneRules_levelTwo = topLine * Math.sqrt(Math.sqrt(frequencyRange));
var toneRules_levelFour = toneRules_levelOne / Math.sqrt(Math.sqrt(frequencyRange));
/*
* Tone rules Levels (semitones) Duration factor
* Tone 1: L 5 - 5, D 1
* Tone 2: L 3(-1) - 5(+1), D 0.8
* Tone 3: L 3 - 1(-3) - 3, D 1.1
* Tone 4: L 5(+2) - 1*, D 0.8
* Tone 0: L 3 - 2, D 0.5
*
* *Tone 4 endpoint is (startPoint - frequencyRange)!
*
*/
var startPoint, midPoint, lowestPoint, endPoint;
// Tone 1
if(currentTone == 1) {
// Just a straight horizontal line
startPoint = toneRules_levelFive
endPoint = toneRules_levelFive
// Two first tones, make them a little different
if(prevTone == 1) {
startPoint = startPoint * 0.999
endPoint = endPoint * 0.999
}
// Write tone points
syllableToneContour.push({"t": time, "f": startPoint});;
time += voicedDuration;
syllableToneContour.push({"t": time, "f": endPoint});;
}
// Tone 2
else if(currentTone == 2) {
// Start halfway of the range - 1 semitone
startPoint = toneRules_levelThree * toneRules_oneSemit
// End 1 semitones above the first tone
endPoint = toneRules_levelFive / toneRules_oneSemit
// Special case: 2 followed by 1, stop short of the top-line
// ie, 5 semitones above the start
if (nextTone == 1) {
endPoint = startPoint / toneRules_fiveSemit
}
// Go lower if previous tone is 1
if (prevTone == 1) {
startPoint = startPoint * toneRules_oneSemit
} else if ( prevTone == 4 || prevTone == 3) {
// Special case: 2 following 4 or 3
// Go 1 semitone up
startPoint = lastFrequency / toneRules_oneSemit
endPoint = toneRules_levelFive
} else if (prevTone == 2) {
// Two consecutive tone 2, start 1 semitone higher
startPoint = startPoint / toneRules_oneSemit
}
// Write points
syllableToneContour.push({"t": time, "f": startPoint});;
// Next point flat to 1/3th of duration
time += voicedDuration / 3;
syllableToneContour.push({"t": time, "f": startPoint});;
// Next point a end
time += voicedDuration * 2 / 3;
syllableToneContour.push({"t": time, "f": endPoint});;
}
// Tone 3
else if(currentTone == 3) {
// Halfway the range
startPoint = toneRules_levelThree
lowestPoint = toneRules_levelOne * toneRules_threeSemit
// Protect pitch against "underflow"
if(lowestPoint < toneRules_absoluteMinimum) {
lowestPoint = toneRules_absoluteMinimum;
}
// First syllable
if (nextTone < 0) {
endPoint = startPoint
// Anticipate rise in next tone
} else if (nextTone == 1 || nextTone == 4) {
lowestPoint = toneRules_levelOne / toneRules_twoSemit
endPoint = startPoint
// Anticipate rise in next tone and stay low
} else if (nextTone == 2) {
lowestPoint = toneRules_levelOne / toneRules_twoSemit
endPoint = lowestPoint
// Last one was low, don't go so much lower
} else if (prevTone == 4) {
lowestPoint = toneRules_levelOne * toneRules_oneSemit
// Anticipate rise in next tone and stay low
} else if (nextTone == 0) {
lowestPoint = toneRules_levelOne
endPoint = lowestPoint / toneRules_sixSemit
} else {
endPoint = startPoint
}
// Write points
syllableToneContour.push({"t": time, "f": startPoint});;
// Go 1/3 of the duration down
time += (voicedDuration)*2/6
syllableToneContour.push({"t": time, "f": lowestPoint});;
// Go half the duration low
time += (voicedDuration)*3/6
syllableToneContour.push({"t": time, "f": lowestPoint});;
// Return in 1/6th of the duration
time += (voicedDuration)*1/6
syllableToneContour.push({"t": time, "f": endPoint});;
}
// Tone 3 with voice break
// Lowest frequencies are voiceless (F0 = 0)
else if(currentTone == 9) {
// Halfway the range
startPoint = toneRules_levelThree
lowestPoint = toneRules_levelOne * toneRules_threeSemit
// Protect pitch against "underflow"
if(lowestPoint < toneRules_absoluteMinimum) {
lowestPoint = toneRules_absoluteMinimum;
}
// First syllable
if (nextTone < 0) {
endPoint = startPoint
// Anticipate rise in next tone
} else if (nextTone == 1 || nextTone == 4) {
lowestPoint = toneRules_levelOne / toneRules_twoSemit
endPoint = startPoint
// Anticipate rise in next tone and stay low
} else if (nextTone == 2) {
lowestPoint = toneRules_levelOne / toneRules_twoSemit
endPoint = lowestPoint
// Last one was low, don't go so much lower
} else if (prevTone == 4) {
lowestPoint = toneRules_levelOne * toneRules_oneSemit
// Anticipate rise in next tone and stay low
} else if (nextTone == 0) {
lowestPoint = toneRules_levelOne
endPoint = lowestPoint / toneRules_sixSemit
} else {
endPoint = startPoint
}
// Write points
syllableToneContour.push({"t": time, "f": startPoint});;
// Go 1/3 of the duration down
time += (voicedDuration)*2/6
syllableToneContour.push({"t": time, "f": lowestPoint});;
// CHECK THIS !!!
// voiceless break
var delta = time + 0.001
syllableToneContour.push({"t": delta, "f": 0});
// Go half the duration low
time += (voicedDuration)*3/6
delta = time - 0.001
syllableToneContour.push({"t": delta, "f": 0});
// After voiceless break
syllableToneContour.push({"t": time, "f": lowestPoint});;
// Return in 1/6th of the duration
time += (voicedDuration)*1/6
syllableToneContour.push({"t": time, "f": endPoint});;
}
// Tone 4
else if(currentTone == 4) {
// Start higher than tone 1 (by 2 semitones)
startPoint = toneRules_levelFive / toneRules_twoSemit
// Go down the full range
endPoint = startPoint * frequencyRange
// SPECIAL: Fall in following neutral tone
if (nextTone == 0) {
endPoint = endPoint / toneRules_threeSemit
}
// Define a midtoneScript.point at 1/3 of the duration
var midPoint = startPoint
// Write points
syllableToneContour.push({"t": time, "f": startPoint});;
// Next point a 1/3th of duration
time += voicedDuration / 3;
syllableToneContour.push({"t": time, "f": startPoint});;
// Next point a end
time += voicedDuration * 2 / 3;
syllableToneContour.push({"t": time, "f": endPoint});;
}
// Tone 0
else if(currentTone == 0) {
if (lastFrequency > 0) {
startPoint = lastFrequency
} else {
startPoint = toneRules_levelThree / toneRules_oneSemit
};
if (prevTone == 1) {
startPoint = lastFrequency * toneRules_twoSemit
} else if (prevTone == 2) {
startPoint = lastFrequency
} else if (prevTone == 3) {
startPoint = lastFrequency / toneRules_oneSemit
} else if (prevTone == 4) {
startPoint = lastFrequency * toneRules_oneSemit
} else if (lastFrequency > 0) {
startPoint = lastFrequency * toneRules_oneSemit
};
// Catch all errors
if (startPoint <= 0) {
startPoint = toneRules_levelThree / toneRules_oneSemit
};
// Add spreading and some small or large de/inclination
if (prevTone == 1) {
midPoint = startPoint * frequencyRange / toneRules_oneSemit
endPoint = midPoint * toneRules_oneSemit
} else if (prevTone == 2) {
midPoint = startPoint * toneRules_fiveSemit
endPoint = midPoint * toneRules_twoSemit
} else if (prevTone == 3) {
midPoint = startPoint / toneRules_twoSemit
endPoint = midPoint
} else if (prevTone == 4) {
midPoint = startPoint * toneRules_threeSemit
endPoint = midPoint / toneRules_oneSemit
} else {
midPoint = startPoint * toneRules_oneSemit
endPoint = midPoint
};
// Write points, first 2/3 then decaying 1/3
syllableToneContour.push({"t": time, "f": startPoint});;
time += (voicedDuration - 1/startPoint) * 2 / 3;
syllableToneContour.push({"t": time, "f": midPoint});;
// Next point a end
time += (voicedDuration - 1/startPoint) * 1 / 3;
syllableToneContour.push({"t": time, "f": endPoint});;
}
// Non-tone intonation
else {
// Start halfway of the range
startPoint = toneRules_levelThree
// Or continue from last Non-"tone"
if (prevTone == 6) {
startPoint = lastFrequency
}
// Add declination
endPoint = startPoint * toneRules_oneSemit
// Write tone points
syllableToneContour.push({"t": time, "f": startPoint});;
time += voicedDuration;
syllableToneContour.push({"t": time, "f": endPoint});;
}
return syllableToneContour;
}
// Create a syllable tone movement
function addToneMovement (time, lastFrequency, syllable, topLine, prevTone, nextTone, toneRange, speedFactor) {
var currentToneContour = [];
// Get tone
var toneSyllable = getTones(syllable);
// Tone sandhi: 3-3/9-9 => 2-3
if ((toneSyllable == 3 || toneSyllable == 9) && (nextTone == 3 || nextTone == 9)) {
toneSyllable = 2
};
// Get voicing pattern
var voicingSyllable = convertVoicing(syllable);
// Account for tones in duration
// Scale the duration of the current syllable
var toneFactor = toneDuration (prevTone, toneSyllable, nextTone);
toneFactor *= speedFactor;
// Unvoiced part
if (voicingSyllable.match(/U/g)) {
time += toneScript_delta;
currentToneContour.push({"t": time, "f": 0});;
time += toneScript_segmentDuration * toneFactor;
currentToneContour.push({"t": time, "f": 0});;
}
// Voiced part
var voicedLength = voicingSyllable.replace(/U*([CV]+)U*/g, "$1").length;
var voicedDuration = toneFactor * (toneScript_segmentDuration * voicedLength + toneScript_fixedDuration)
time += toneScript_delta;
/*
* Write contour of each tone
* Note that tones are influenced by the previous (tone 0) and next (tone 3)
* tones. Tone 6 is the NO TONE intonation
* sqrt(frequencyRange) is the mid point
*
*/
var voicedContour = toneRules (topLine, time, lastFrequency, voicedDuration, prevTone, toneSyllable, nextTone, toneRange);
currentToneContour = currentToneContour.concat(voicedContour);
return currentToneContour;
}
// Take a word and create tone contour
// !!! Add addapted highest tone and range !!!
function word2tones (pinyin, topLine) {
var pitchTier = word2scaledTones (pinyin, topLine, 1, 1);
return pitchTier;
};
function word2scaledTones (pinyin, topLine, toneRange, speedFactor) {
var toneContour = [];
var word;
var pinyinWithSpaces = pinyin.replace(/([\d]+)/g, "$1 ");
pinyinWithSpaces = pinyinWithSpaces.replace(/ $/, "");
var syllableList = pinyinWithSpaces.split(" ");
// Start toneContour with margin
var time = 0;
toneContour.push({"t": time, "f": 0});;
time += toneScript_margin
toneContour.push({"t": time, "f": 0});;
lastFrequency = 0;
for(s = 0; s < syllableList.length; ++s) {
var prevTone = -1;
var nextTone = -1;
var syllable = syllableList[s];
if(s-1 >= 0) prevTone = Number(syllableList[s-1].replace(/[^\d]+/g, ""));
if(s+1 < syllableList.length) nextTone = Number(syllableList[s+1].replace(/[^\d]+/g, ""));
var syllableContour = addToneMovement (time, lastFrequency, syllable, topLine, prevTone, nextTone, toneRange, speedFactor);
toneContour = toneContour.concat(syllableContour);
time = toneContour[(toneContour.length - 1)].t;
lastFrequency = toneContour[(toneContour.length - 1)].f;
};
// Trailing margin
time += toneScript_delta;
toneContour.push({"t": time, "f": 0});;
time += toneScript_margin
toneContour.push({"t": time, "f": 0});
/* Create PitchTier
* { "xmin": 0, "xmax": duration, "points": [{"t": t, "f":, f},{}]}
*
*/
// First create points
var points = [];
var timeSeries = [];
var valueSeries = [];
var pitchTier = new Tier ();
pitchTier.dT = dx;
for(x = dx/2; x < time; x += dx) {
// Locate tone stretch
var i = 0;
for(i=0; i< toneContour.length && toneContour[i].t < x; ++i) ;
// Interpolate tone if BOTH are non-zero
var value = 0;
var prefT = toneContour[i-1].t;
var prefF = toneContour[i-1].f;
var nextT = toneContour[i].t;
var nextF = toneContour[i].f;
// When the second part is "0", it is treated as a string concatenation
if(prefF > 0 && nextF > 0) {
value = Number(prefF) + Number((x - prefT)/(nextT - prefT)*(nextF - prefF));
}
pitchTier.pushItem({"x": x, "value": value});
};
return pitchTier;
}
// Filter pitchTier to get more realistic joins
function smooth_pitchTier (pitchTier) {
var prevTime = -1;
var prevValue = 0;
var currentTime = -1;
var currentValue = 0;
for(var i = 1; i < pitchTier.size; i+=1) {
var item = pitchTier.item(i);
nextTime = item.x;
nextValue = item.value;
// Change currentValue as the average of prev, current, and next
// NOTE: Do not use the changed value for the next round!!!
if (prevValue > 0 && currentValue > 0 && nextValue > 0) {
var item = pitchTier.item(i-1);
item.value = (prevValue + currentValue + nextValue) / 3;
pitchTier.writeItem(i-1, item);
};
// Next round
prevTime = currentTime;
prevValue = currentValue;
currentTime = nextTime;
currentValue = nextValue;
};
};
// Plot the pitch tier on the canvas
function plot_pitchTier (canvasId, color, lineWidth, topLine, pitchTier) {
var drawingCtx = setDrawingParam(canvasId);
var plotWidth = drawingCtx.canvas.width
var plotHeight = drawingCtx.canvas.height
// Set parameters
drawingCtx.beginPath();
drawingCtx.strokeStyle = color;
drawingCtx.lineWidth = lineWidth;
// Scale to plot area
var tmin = pitchTier.xmin;
var tmax = pitchTier.xmax;
var tScale = plotWidth / (pitchTier.xmax - pitchTier.xmin);
var vScale = plotHeight / (2*topLine - 0.4*topLine);
var prevTime = -1;
var prevValue = 0;
for(var i = 1; i < pitchTier.size; i+=1) {
var item = pitchTier.item(i);
currentTime = item.x;
currentValue = item.value;
if(prevValue > 0 && currentValue > 0) {
drawingCtx.lineTo(currentTime * tScale, plotHeight - currentValue * vScale);
} else if (prevValue <= 0 && currentValue > 0) {
drawingCtx.moveTo(currentTime * tScale, plotHeight - currentValue * vScale);
} else if (prevValue > 0 && currentValue <= 0) {
drawingCtx.stroke();
};
prevTime = currentTime;
prevValue = currentValue;
};
drawingCtx.stroke();
};
function draw_example_pinyin (id, pinyin) {
if (pinyin.match(/\d/)) {
topLine = getRegister();
var pitchTier = word2tones (pinyin, topLine);
smooth_pitchTier (pitchTier);
plot_pitchTier (id, "green", 8, topLine, pitchTier);
} else {
setDrawingParam(id);
};
};
function draw_test_signal (Id, pinyin) {
topLine = getRegister();
var pitchTier = testPitchTracker (2, 44100);
plot_pitchTier (Id, "blue", 8, topLine, pitchTier);
};
var lightSize = 15;
var maxPowerRecorded = 90;
var thresshold = 0.1;
function display_recording_level (id, recordedArray) {
var sumSquare = 0;
var nSamples = 0;
for (var i = 0; i < recordedArray.length; ++i) {
if(Math.abs(recordedArray[i]) > thresshold) {
sumSquare += recordedArray[i] * recordedArray[i];
++nSamples;
};
};
var power = sumSquare / nSamples;
var dBpower = (power > 0) ? maxPowerRecorded + 2*Math.log10(power) * 10 : 0;
var recordingLight = document.getElementById(id);
var currentWidth = 100*recordingLight.clientWidth/window.innerWidth;
var currentHeight = 100*recordingLight.clientHeight/window.innerHeight;
var horMidpoint = 5 + currentWidth/2;
var verMidpoint = 5 + currentHeight/2;
// New fontSize
var fontSize = lightSize*dBpower/maxPowerRecorded + 1;
recordingLight.style.fontSize = fontSize + "vmin";
// position = midpoint - newFontSize / 2
recordingLight.style.top = (verMidpoint - ((fontSize/lightSize)*currentHeight)/2) + "%";
recordingLight.style.left = (horMidpoint - ((fontSize/lightSize)*currentWidth)/2) + "%";
};
function draw_tone (id, color, typedArray, sampleRate) {
var fMin = 75;
var fMax = 600;
var dT = 0.01;
var topLine = getRegister();
pitchTier = toPitchTier (typedArray, sampleRate, fMin, fMax, dT);
plot_pitchTier (id, color, 4, topLine, pitchTier);
return pitchTier;
}
var recognition = {
Recognition: "",
Feedback: "",
Label: "Correct",
Register: "OK",
Range: "OK",
Proficiency: -1
};
// currentLesson is defined!!!
function recognition2performance (pinyin, recognition, performanceRecord) {
if (! performanceRecord [currentLesson] )
performanceRecord [currentLesson] = {};
var wordList = performanceRecord [currentLesson];
if (! wordList[pinyin] ) {
wordList[pinyin] = {
"Grade" : -1,
"Correct" : 0,
"Wrong" : 0,
"High" : 0,
"Low" : 0,
"Wide" : 0,
"Narrow" : 0,
"Proficiency" : -1,
"Date" : "",
"Lesson" : currentLesson,
"Mark" : currentItem[1],
"Character" : currentItem[2],
"Translation" : currentItem[3],
"Example" : currentItem[currentItem.length - 1]
};
};
if (Object.keys(recognition).length > 0) {
++wordList[pinyin][recognition.Label];
if(recognition.Register != "OK")++wordList[pinyin][recognition.Register];
if(recognition.Range != "OK")++wordList[pinyin][recognition.Range];
var d = new Date();
wordList[pinyin]["Proficiency"] = recognition.Proficiency;
wordList[pinyin]["Date"] = d.toLocaleDateString() + " " + d.toLocaleTimeString();
};
// Write performance table to storage
var objectList = performanceRecord2objectList (performanceRecord);
writeCSV(sgc3_settings.currentCollection, objectList);
};
// currentLesson is defined!!!
function setGRADE (pinyin, grade) {
var wordList = performanceRecord [currentLesson];
if (wordList && wordList[pinyin] ) {
wordList[pinyin].Grade = grade == 0 ? 10 : grade;
// Write performance table to storage
var objectList = performanceRecord2objectList (performanceRecord);
writeCSV(sgc3_settings.currentCollection, objectList);
// Display grade
document.getElementById("GradeString").textContent = wordList[pinyin].Grade;
};
};
function performanceRecord2objectList (performanceRecord) {
var objectList = [];
lessonList = Object.keys(performanceRecord);
for (var l=0; l<lessonList.length; ++l) {
var lesson = lessonList[l];
var wordList = Object.keys(performanceRecord[lesson]);
for (var p=0; p<wordList.length; ++p) {
var pinyin = wordList[p];
var record = performanceRecord[lesson][pinyin];
objectList.push({
"Pinyin": pinyin,
"Grade" : record.Grade,
"Correct" : record.Correct,
"Wrong" : record.Wrong,
"High" : record.High,
"Low" : record.Low,
"Wide" : record.Wide,
"Narrow" : record.Narrow,
"Proficiency": record.Proficiency,
"Date" : record.Date,
"Lesson" : record.Lesson,
"Mark" : record.Mark,
"Character" : record.Character,
"Translation" : record.Translation,
"Example" : record.Example
});
};
};
return objectList;
};
function objectList2performanceRecord (objectList) {
var performanceRecord = {};
var headerList = Object.keys(objectList[0]);
for (var i=0; i<objectList.length; ++i) {
var record = objectList[i];
if(!record.Lesson) continue;
if(!performanceRecord[record.Lesson])performanceRecord[record.Lesson] = {};
performanceRecord[record.Lesson][record.Pinyin] = {
"Grade" : record.Grade,
"Correct" : record.Correct,
"Wrong" : record.Wrong,
"High" : record.High,
"Low" : record.Low,
"Wide" : record.Wide,
"Narrow" : record.Narrow,
"Proficiency": record.Proficiency,
"Date" : record.Date,
"Lesson" : record.Lesson,
"Mark" : record.Mark,
"Character" : record.Character,
"Translation" : record.Translation,
"Example" : record.Example
};
};
return performanceRecord;
};
// Handle sound after decoding (used in audioProcessing.js)
function processRecordedSound () {
if(recordedArray) {
display_recording_level ("RecordingLight", recordedArray);
initializeDrawingParam ("TonePlot");
draw_example_pinyin ("TonePlot", currentPinyin);
if (recordedPitchTier) {
plot_pitchTier ("TonePlot", "red", 4, getRegister(), recordedPitchTier);
} else {
recordedPitchTier = draw_tone ("TonePlot", "red", recordedArray, recordedSampleRate)
};
recognition = sgc_ToneProt (pitchTier, currentPinyin, sgc3_settings.register, sgc3_settings.strict, sgc3_settings.language);
// Only do this ONCE for every recording
if(sgc3_settings.saveAudio) {
if (sessionStorage.recorded == "true") {
saveCurrentAudioWindow (sgc3_settings.currentCollection, currentLesson, currentPinyin+".wav");
recognition2performance(currentPinyin, recognition, performanceRecord);
} else {
// Create empty record
recognition2performance(currentPinyin, {}, performanceRecord);
};
};
// Write results
document.getElementById("ResultString").textContent = recognition.Recognition;
document.getElementById("ResultString").style.color = (recognition.Label == "Correct") ? "green" : "red";
document.getElementById("FeedbackString").textContent = recognition.Feedback;
var feedbackOK = recognition.Label == "Correct" && recognition.Register == "OK" && recognition.Range == "OK";
document.getElementById("FeedbackString").style.color = feedbackOK ? "green" : "red";
document.getElementById("FeedbackString").style.fontSize = recognition.Feedback.length > 70 ? "2.5vmin" : (recognition.Feedback.length > 50 ? "3.5vmin" : "4vmin");
// Write out grade
if(performanceRecord && performanceRecord [currentLesson] && performanceRecord [currentLesson][currentPinyin].Grade >=0) {
document.getElementById("GradeString").textContent = performanceRecord [currentLesson][currentPinyin].Grade;
};
// Set play button
if(currentAudioWindow.length > 0) {
document.getElementById('PlayButton').disabled = false;
document.getElementById('PlayButton').style.color = "red";
};
};
};
// Tone recogition
// Set up the tone context and start recognition
function sgc_ToneProt (pitchTier, pinyin, register, proficiency, language) {
var recognitionText = numbersToTonemarks(pinyin)+": ";
var feedbackText = "";
var labelText = "";
var topLine = getRegister();
// Clean up pinyin
// Remove spaces
pinyin = pinyin.replace(/^\s*(.+)\s*$/g, "$1");
// 5 used as neutral tone number
pinyin = pinyin.replace(/5/g, "0");
// Add missing neutral tones
pinyin = add_missing_neutral_tones (pinyin);
// Create a model tone pronunciation
var tonePitchTier = word2tones (pinyin, topLine);
// Set up recognition values
var precision = 3;
if (proficiency >= 3) {
precision = 1.5
};
if(pinyin.match(/3/))precision *= 4/3;
// Stick to the raw recognition results or not
var ultraStrict = (proficiency >= 3);
// Reduction (lower sgc_ToneProt.register and narrow range) means errors
// The oposite mostly not. Asymmetry alows more room upward
// than downward (asymmetry = 2 => highBoundaryFactor ^ 2)
var asymmetry = 2;
var spacing = 0.5;
var speedFactor = 1;
var speechDuration = pitchTier.xmax;
var modelDuration = tonePitchTier.xmax;
var precisionFactor = Math.pow(2,(precision/12));
var highBoundaryFactor = Math.pow(precisionFactor, asymmetry);
var lowBoundaryFactor = 1/precisionFactor
// Get top and range of model
var tonePercentiles = get_percentiles (tonePitchTier.valueSeries(), function (a, b) { return a-b;}, function(a) { return a <= 0;}, [5, 95]);
maximumModelFzero = (tonePercentiles[1].value > 0) ? tonePercentiles[1].value : 0;
minimumModelFzero = (tonePercentiles[0].value > 0) ? tonePercentiles[0].value : 0;
var modelPitchRange = 2; // 1 octave
if (minimumModelFzero > 0) {
modelPitchRange = maximumModelFzero / minimumModelFzero;
} else {
modelPitchRange = 0
};
// Get top and range of recorded word
var pitchPercentiles = get_percentiles (pitchTier.valueSeries(), function (a, b) { return a-b;}, function(a) { return a <= 0;}, [5, 95]);
maximumRecFzero = pitchPercentiles[1].value > 0 ? pitchPercentiles[1].value : 0;
minimumRecFzero = pitchPercentiles[0].value > 0 ? pitchPercentiles[0].value : 0;
var recPitchRange = 2; // 1 octave
if (minimumRecFzero > 0) {
recPitchRange = maximumRecFzero / minimumRecFzero;
} else {
recPitchRange = 0;
};
var recordedMinMax = get_time_of_minmax (pitchTier);
// Rescale register (ignore model tone ranges <= 3 semitones)
newRegister = (maximumModelFzero > 0) ? maximumRecFzero / maximumModelFzero * register : register;
newToneRange = (modelPitchRange > 1/toneRules_threeSemit) ? recPitchRange / modelPitchRange : 1;
// Advanced speakers must not speak too High, or too "Dramatic"
// Beginning speakers also not too Low or too Narrow ranges
var registerUsed = "OK";
var rangeUsed = "OK";
if (newRegister > highBoundaryFactor * register) {
newRegister = highBoundaryFactor * register;
registerUsed = "High"
} else if ( proficiency < 3 && newRegister < lowBoundaryFactor * register) {
newRegister = lowBoundaryFactor * register;
registerUsed = "Low"
};
if (newToneRange > highBoundaryFactor) {
newToneRange = highBoundaryFactor
rangeUsed = "Wide"
} else if (proficiency < 3 && newToneRange < lowBoundaryFactor) {
//Don't do this for advanced speakers
newToneRange = lowBoundaryFactor;
rangeUsed = "Narrow";
};
// Duration
if (modelDuration > spacing) {
speedFactor = (speechDuration - spacing) / (modelDuration - spacing)
};
// Round values
newRegister = Math.round(newRegister);
// Remove all pitch points outside a band around the newRegister
var upperCutOff = 1.5*newRegister;
var lowerCutOff = newRegister/3;
for (var i=0; i < pitchTier.size; ++i) {
var item = pitchTier.item(i);
if(item.value > upperCutOff || item.value < lowerCutOff) {
item.value = 0;
pitchTier.writeItem(i, item);
};
};
// Do the tone recognition
// Step through longer words
var syllableCount = numSyllables (pinyin);
var choiceReference = pinyin;
var skipSyllables = 0;
while (choiceReference == pinyin && skipSyllables+1 < Math.max(syllableCount,2)) {
var result = freeToneRecognition(pitchTier, choiceReference, newRegister, newToneRange, speedFactor, proficiency, skipSyllables);
skipSyllables += 1
choiceReference = result.pinyin;
// Get rid of odd symbols
choiceReference = choiceReference.replace(/9/g, "3");
};
// Special cases (frequent recognition errors)
// Not ultra strict and wrong
//
// !!! Add rules for 3[12] to 30 confusions, 00 misidentification !!!
if (proficiency < 3 && choiceReference != pinyin) {
var currentPinyin = choiceReference;
// [23]3 is often misidentified as 23, 20 or 30
var matchedFragmentList = pinyin.match(/[23][^0-9]+3/g);
while (matchedFragmentList && matchedFragmentList.length > 0) {
var matchedFragment = matchedFragmentList.shift();
var matchedSyllable = matchedFragment.replace(/[23]/g, "");
currentPinyin = currentPinyin.replace(new RegExp("[23]"+matchedSyllable+"[023]", 'g'), matchedFragment)
};
// First syllable: 2<->3 exchanges
// 3 => 2
var matchedFragmentList = pinyin.match(/[^[^0-9]+2/g);
while (matchedFragmentList && matchedFragmentList.length > 0) {
var matchedFragment = matchedFragmentList.shift();
var matchedSyllable = matchedFragment.replace(/[23]/g, "");
currentPinyin = currentPinyin.replace(new RegExp("^"+matchedSyllable+"[3]", 'g'), matchedFragment)
};
// 2 => 3
var matchedFragmentList = pinyin.match(/[^[^0-9]+3/g);
while (matchedFragmentList && matchedFragmentList.length > 0) {
var matchedFragment = matchedFragmentList.shift();
var matchedSyllable = matchedFragment.replace(/[23]/g, "");
currentPinyin = currentPinyin.replace(new RegExp("^"+matchedSyllable+"[2]", 'g'), matchedFragment)
};
// A single second tone is often misidentified as a neutral tone,
// A real neutral tone would be too low or too narrow and be discarded
// 0 => 2
var matchedFragmentList = pinyin.match(/^[^0-9]+2$/g);
while (matchedFragmentList && matchedFragmentList.length > 0) {
var matchedFragment = matchedFragmentList.shift();
var matchedSyllable = matchedFragment.replace(/[2]/g, "");
if (recordedMinMax.tmin < recordedMinMax.tmax) {
currentPinyin = currentPinyin.replace(new RegExp("^"+matchedSyllable+"[0]", 'g'), matchedFragment);
};
};
// A single fourth tone is often misidentified as a neutral tone,
// A real neutral tone would be too low or too narrow and be discarded