forked from 1heisuzuki/speech-to-text-webcam-overlay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
executable file
·1059 lines (955 loc) · 50.9 KB
/
index.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 prefix="og: http://ogp.me/ns">
<meta charset=utf-8 />
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<title>Speech to Text Webcam Overlay</title>
<meta name="description" content="Web Speech API で音声認識した結果の字幕をWebカメラ映像に重ねて表示するWebページです。ブラウザを画面収録して,ビデオ会議や生配信等で使用できます。">
<meta property="og:title" content="Speech to Text Webcam Overlay" />
<meta property="og:description" content="Web Speech API で音声認識した結果の字幕をWebカメラ映像に重ねて表示するWebページです。ブラウザを画面収録して,ビデオ会議や生配信等で使用できます。" />
<meta property="og:url" content="https://1heisuzuki.github.io/speech-to-text-webcam-overlay/">
<meta property="og:image" content="https://1heisuzuki.github.io/speech-to-text-webcam-overlay/thumbnail.jpg">
<meta name="twitter:card" content="summary">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css?ver=202005300200" type="text/css" media="screen" charset="utf-8" />
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script src="kuromoji/build/kuromoji.js"></script>
</head>
<body>
<div class="main">
<div id="status" class="error">起動中...</div>
<div id="status_kuromoji_loading" class="hidden"></div>
<div id="video_wrapper" class="video_wrapper">
<video id="result_video" class="video_area" autoplay></video>
<div id="video_bg" class="video_bg hidden"></div>
<div id="text_overlay_wrapper" class="text_overlay_wrapper full">
<div id="text_bg" class="text_bg"></div>
<div id="result_text" class="text_area">音声認識が始まるとここに文字が表示されます。マイクとカメラを有効にしてください。</div>
</div>
<!-- <input type="button" id="FullScreenBtn" class="FullScreenBtn" value="全画面"> -->
<img src="fullscreen.svg" id="FullScreenBtn" class="FullScreenBtn" width="18" height="18" style="display:block">
</div>
<div class="help_text log_link_description"><a href="#log">認識結果のログ表示/ダウンロード</a></div>
<div id="help_on_error" class="help_on_error">
カメラやマイクが機能しないとき → ページの再読み込みや,ブラウザの設定を確認してください: <a
href="https://support.google.com/chrome/answer/2693767?co=GENIE.Platform%3DDesktop&hl=ja&oco=1"
target="_blank">Chrome ヘルプ</a>
</div>
<div class="controls_wrapper control_wrapper_row">
<div class="col-12 control_wrapper_col">
<div class="control_header">文字の調整</div>
<div class="control_wrapper" style="padding-top: 0.8rem;">
<div class="control_form control_form_slider col-3">
<label for="slider_font_size" class="control_label">大きさ</label>
<input id="slider_font_size" type="range" class="control_input" value="68" min="1" max="150" step="1"
oninput="document.getElementById('result_text').style.fontSize=this.value+'px',document.getElementById('value_font_size').innerHTML=this.value">
<div class="control_value">
<span id="value_font_size">68</span><span class="value_unit">px</span>
</div>
</div>
<div class="control_form control_form_slider col-3">
<label for="slider_opacity" class="control_label">透明度</label>
<input id="slider_opacity" type="range" class="control_input" value="0.9" min="0" max="1" step="0.05"
oninput="document.getElementById('result_text').style.opacity=this.value,document.getElementById('value_opacity').innerHTML=this.value">
<div class="control_value">
<span id="value_opacity">0.9</span>
</div>
</div>
<div class="control_form control_form_radio col-4">
<label for="selector_position" class="control_label">位置</label>
<div class="control_input">
<label for="selector_position_full">
<input id="selector_position_full" type="radio" name='selector_position'
oninput="document.getElementById('text_overlay_wrapper').className='text_overlay_wrapper full'" checked> 全体
</label>
<label for="selector_position_left">
<input id="selector_position_left" type="radio" name='selector_position'
oninput="document.getElementById('text_overlay_wrapper').className='text_overlay_wrapper split left'"> 左
</label>
<label for="selector_position_right">
<input id="selector_position_right" type="radio" name='selector_position'
oninput="document.getElementById('text_overlay_wrapper').className='text_overlay_wrapper split right'"> 右
</label>
<label for="selector_position_top">
<input id="selector_position_top" type="radio" name='selector_position'
oninput="document.getElementById('text_overlay_wrapper').className='text_overlay_wrapper split top'"> 上
</label>
<label for="selector_position_bottom">
<input id="selector_position_bottom" type="radio" name='selector_position'
oninput="document.getElementById('text_overlay_wrapper').className='text_overlay_wrapper split bottom'"> 下
</label>
</div>
</div>
<div class="control_form control_form_slider col-3">
<label for="slider_text_shadow_stroke" class="control_label">影</label>
<input id="slider_text_shadow_stroke" type="range" class="control_input" value="5" min="0" max="20" step="0.1"
oninput="document.getElementById('result_text').style.textShadow='0 0 '+this.value+'px '+document.getElementById('selector_text_shadow_color').value,document.getElementById('value_text_shadow_stroke').innerHTML=this.value">
<div class="control_value">
<span id="value_text_shadow_stroke">5</span><span class="value_unit">px</span>
</div>
</div>
<div class="control_form control_form_slider col-3">
<label for="slider_text_stroke" class="control_label">フチ</label>
<input id="slider_text_stroke" type="range" class="control_input" value="0.3" min="0" max="5" step="0.01"
oninput="document.getElementById('result_text').style.webkitTextStrokeWidth=this.value+'px',document.getElementById('value_text_stroke').innerHTML=this.value">
<div class="control_value">
<span id="value_text_stroke">0.3</span><span class="value_unit">px</span>
</div>
</div>
<div class="control_form control_form_slider col-3">
<label for="slider_line_height" class="control_label">行間</label>
<input id="slider_line_height" type="range" class="control_input" value="163" min="100" max="300" step="1"
oninput="document.getElementById('result_text').style.lineHeight=this.value+'%',document.getElementById('value_line_height').innerHTML=this.value">
<div class="control_value">
<span id="value_line_height">163</span><span class="value_unit">%</span>
</div>
</div>
<div class="control_form control_form_slider col-3">
<label for="slider_letter_spacing" class="control_label">字間</label>
<input id="slider_letter_spacing" type="range" class="control_input" value="0.05" min="0" max="1" step="0.01"
oninput="document.getElementById('result_text').style.letterSpacing=this.value+'em',document.getElementById('value_letter_spacing').innerHTML=this.value">
<div class="control_value">
<span id="value_letter_spacing">0.05</span>
</div>
</div>
<div class="control_form control_form_color col-2">
<label for="selector_text_color" class="control_label">文字色</label>
<input id="selector_text_color" type="color" class="control_input" value="#ffffff"
oninput="document.getElementById('result_text').style.color=this.value">
</div>
<div class="control_form control_form_color col-2">
<label for="selector_text_shadow_color" class="control_label">影色</label>
<input id="selector_text_shadow_color" type="color" class="control_input" value="#000000"
oninput="document.getElementById('result_text').style.textShadow='0 0 '+document.getElementById('slider_text_shadow_stroke').value+'px '+this.value">
</div>
<div class="control_form control_form_color col-2">
<label for="selector_text_stroke_color" class="control_label">フチ色</label>
<input id="selector_text_stroke_color" type="color" class="control_input" value="#000000"
oninput="document.getElementById('result_text').style.webkitTextStrokeColor=this.value">
</div>
<div class="control_form control_form_selector col-3">
<label for="select_font" class="control_label">フォント </label>
<select id="select_font" onchange="document.getElementById('result_text').style.fontFamily=fonts_custom[select_font.selectedIndex][1]" style="width: 94%; height: 100%;"></select>
</div>
<div class="control_form control_form_selector col-2">
<label for="select_autoclear_text" class="control_label">自動消去 </label>
<select id="select_autoclear_text" onchange="updateTextClearSecond()">
<option value="0">なし</option>
<option value="5">5秒</option>
<option value="10">10秒</option>
<option value="20">20秒</option>
<option value="30" selected>30秒</option>
<option value="45">45秒</option>
<option value="60">1分</option>
</select>
</div>
</div>
</div>
<div class="col-6 control_wrapper_col">
<div class="control_header">文字背景の塗り調整</div>
<div class="control_wrapper">
<div class="control_form control_form_slider col-6">
<label for="slider_text_bg_opacity" class="control_label">濃さ</label>
<input id="slider_text_bg_opacity" type="range" class="control_input" value="0.3" min="0" max="1" step="0.05"
oninput="document.getElementById('text_bg').style.opacity=this.value,document.getElementById('value_text_bg_opacity').innerHTML=this.value">
<div class="control_value">
<span id="value_text_bg_opacity">0.3</span>
</div>
</div>
<div class="control_form control_form_color col-6">
<label for="selector_text_bg_color" class="control_label">色</label>
<input id="selector_text_bg_color" type="color" class="control_input" value="#000000"
oninput="document.getElementById('text_bg').style.backgroundColor=this.value">
</div>
</div>
</div>
<div class="col-6 control_wrapper_col">
<div class="control_header">単色背景の調整</div>
<div class="control_wrapper">
<div class="control_button_wrapper col-6">
<input type="button" id="video_bg_toggle" class="" value="単色背景 表示/非表示"
onclick="toggleClass('video_bg','hidden')">
</div>
<div class="control_form control_form_color col-5">
<label for="selector_video_bg" class="control_label">背景色</label>
<input id="selector_video_bg" type="color" class="control_input" value="#00ff00"
oninput="document.getElementById('video_bg').style.backgroundColor=this.value">
</div>
</div>
</div>
<div class="control_button_wrapper">
<input type="button" value="カメラ 表示/非表示"
onclick="toggleClass('result_video','hidden')">
<input type="button" value="カメラ 左右反転"
onclick="toggleClass('result_video','mirror')">
<input type="button" value="文字 表示/非表示"
onclick="toggleClass('text_overlay_wrapper','hidden')">
<input type="button" value="文字 左右反転"
onclick="toggleClass('text_overlay_wrapper','mirror')">
<input type="button" value="全画面化ボタン 表示/非表示"
onclick="toggleClass('FullScreenBtn','hidden')">
<input type="button" value="設定の初期化"
onclick="deleteConfig()">
</div>
<div class="control_selector_wrapper">
カメラ:
<select id="select_camera" onchange="setupCamera()"></select>
</div>
<div class="control_selector_wrapper">
音声認識:
<select id="select_language" class="selector" onchange="updateCountry()"></select>
<select id="select_dialect" class="selector" onchange="updateLanguage()"></select>
<span id="checkbox_hiragana_wrapper" class="selector">
ひらがな<a href="https://github.com/1heisuzuki/speech-to-text-webcam-overlay#ひらがなで表示したい" target="_blank">[?]</a>: <input type="checkbox" id="checkbox_hiragana" name="checkbox_hiragana" value="hiragana" oninput="initKuromoji(this)">
</span>
翻訳:
<div id="google_translate_element" class="select_translation selector"></div>
</div>
<div class="control_selector_wrapper">
音声認識の結果をslackに投稿する: <input type="checkbox" id="checkbox_slack" name="checkbox_slack" value="slack"><br/>
webhook_URL: <input type="text" id="textbox_slack_url">
channel: <input type="text" id="textbox_slack_channel">
表示名: <input type="text" id="textbox_slack_user_name">
</div>
</div>
<div id="log" class="log_wrapper">
<div class="control_header">認識結果のログ</div>
<div class="log_control_wrapper help_text">
*認識結果が確定したタイミングで反映されます。テキストの編集・コピーも可能です。<br/>
**認識中にEnterキーを押すと,認識を止めて文を区切ることができます。日本語の場合は文末に句点が付与されます。</span>
<div class="log_input_wrapper">
時刻の記録: <input type="checkbox" id="checkbox_timestamp" name="checkbox_timestamp" value="timestamp">
</div>
</div>
<textarea id="result_log" class="result_log_area" onchange="textAreaHeightSet(this)"></textarea><br/>
<div style="text-align: center; opacity: 0.6;">
<input type="button" value="ログをダウンロード" onclick="downloadLogFile(this)">
</div>
</div>
<div class="help_wrapper">
<div class="help_text">
よくある質問・ソースコード: <a href="https://github.com/1heisuzuki/speech-to-text-webcam-overlay" target="_blank">GitHub</a><br />
音声認識は <a href="https://developer.mozilla.org/ja/docs/Web/API/Web_Speech_API" target="_blank">Web Speech
API</a> を利用しています。<br />
カメラやマイクが機能しないとき → ページの再読み込みや,ブラウザの設定を確認してください: <a
href="https://support.google.com/chrome/answer/2693767?co=GENIE.Platform%3DDesktop&hl=ja&oco=1"
target="_blank">Chrome ヘルプ</a><br />
「ログをダウンロード」でダウンロードされるファイルは,アクセスしているユーザーのブラウザで生成されています。
</div>
</div>
</div>
</body>
<!-- Chrome で MediaDevices.enumerateDevices() を動かすためのpolyfill -->
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script>
// ブラウザ判定
// 参考: https://qiita.com/sakuraya/items/33f93e19438d0694a91d
var userAgent = window.navigator.userAgent.toLowerCase();
var isChrome = 0;
if (userAgent.indexOf('msie') != -1 || userAgent.indexOf('trident') != -1) {
// IE
} else if (userAgent.indexOf('edge') != -1) {
// Edge
} else if (userAgent.indexOf('chrome') != -1) {
// Chrome
isChrome = 1;
} else if (userAgent.indexOf('safari') != -1) {
// Safari
} else if (userAgent.indexOf('firefox') != -1) {
// Firefox
} else if (userAgent.indexOf('opera') != -1) {
// Opera
} else {
// その他
}
if (!isChrome) {
alert('Google Chromeでアクセスしてください')
document.getElementById('status').innerHTML = "Google Chromeでアクセスしてください";
document.getElementById('status').className = "error";
exit;
}
// Webカメラ
// 参考: https://qiita.com/qiita_mona/items/e58943cf74c40678050a
// getUserMedia が使えないとき
if (typeof navigator.mediaDevices.getUserMedia !== 'function') {
const err = new Error('getUserMedia()が使用できません');
alert(`${err.name} ${err.message}`);
throw err;
}
const $video = document.getElementById('result_video'); // 映像表示エリア
// select要素のoptionをクリアする
function clearSelect(select) {
while(select.firstChild) {
select.removeChild(select.firstChild);
}
}
// select要素のoptionに、option.valueがvalueな項目があれば選択する
// 戻り値は、option中に該当項目があればtrue
function selectValueIfExists(select, value) {
if (value === null || value === undefined) return;
var result = false;
select.childNodes.forEach(n => {
if (n.value === value) {
select.value = value;
result = true;
}
})
return result;
}
// カメラを列挙して select_camera オブジェクトの option に設定
// 参考:https://github.com/webrtc/samples/blob/gh-pages/src/content/devices/input-output/js/main.js
// deviceInfos : MediaDeviceInfo[]
// 引数は MediaDevices.enumerateDevices() の戻り値の Promise の中身という前提
// 参考:https://developer.mozilla.org/ja/docs/Web/API/MediaDevices/enumerateDevices
function updateCameraSelector(deviceInfos) {
// 選んだ項目を最後で再度選ぶために記憶
const selectedDevice = select_camera.value;
// 既存の選択肢をクリア
clearSelect(select_camera);
// メディアデバイス一覧のうち、videoinputをoption要素としてselectに追加
for (let i=0 ; i !== deviceInfos.length ; ++i) {
const deviceInfo = deviceInfos[i];
if (deviceInfo.kind === 'videoinput') {
const option = document.createElement('option');
option.value = deviceInfo.deviceId;
option.text = deviceInfos[i].label || `camera ${select_camera.length + 1}`;
select_camera.appendChild(option);
}
}
// 元々選んでいた項目があれば、その項目を再度選択
selectValueIfExists(select_camera, selectedDevice);
}
// video要素にstreamを設定し、メディア(カメラ、マイク)一覧を返す
// 参考:https://github.com/webrtc/samples/blob/gh-pages/src/content/devices/input-output/js/main.js
function handleStream(stream) {
window.stream = stream;
$video.srcObject = stream;
return navigator.mediaDevices.enumerateDevices();
}
// 設定に基づきカメラ映像を表示
// isInit : カメラ選択肢がない場合だけtrue、他(選択肢切替時や保存された設定からの復元時)は不要
// 参考:https://github.com/webrtc/samples/blob/gh-pages/src/content/devices/input-output/js/main.js
function setupCamera(isInit) {
if (window.stream) {
window.stream.getTracks().forEach(track => {
track.stop();
});
}
const videoSource = select_camera.value;
const constraints = {
video: {
aspectRatio: { ideal: 1.7777777778 }
},
audio: false
};
if (isInit !== true) {
constraints.video["deviceId"] = videoSource ? {exact: videoSource} : undefined;
}
navigator.mediaDevices.getUserMedia(constraints)
.then(handleStream)
.then(updateCameraSelector)
.catch(onCameraError);
}
// カメラ初回起動
function initCamera() {
const conf = JSON.parse(localStorage.speech_to_text_config || '{}');
var camera_selected = false;
if (typeof conf.select_camera !== 'undefined') {
if (selectValueIfExists(select_camera, conf.select_camera)) {
// カメラ選択肢が保存され、selectのoption中にあれば選択されたカメラを起動
camera_selected = true;
setupCamera();
}
}
if (!camera_selected) {
// カメラ設定がされていなければ、デフォルトカメラで開始
setupCamera(true); // 引数はデフォルトカメラ選択の意
}
}
function onCameraError(err) {
console.log(`カメラ関連の問題:${err.name} / ${err.message}`)
alert(`カメラ映像を読み込めませんでした。ブラウザのアクセス制限など,設定を確認してください`);
document.getElementById('help_on_error').style.display='block';
}
// カメラの選択肢を生成
navigator.mediaDevices.enumerateDevices()
.then(updateCameraSelector)
.then(initCamera)
.catch(onCameraError);
// 音声認識
// 参考: https://jellyware.jp/kurage/iot/webspeechapi.html
var flag_speech = 0;
var recognition;
var lang = 'ja-JP';
var textUpdateTimeoutID = 0;
var textUpdateTimeoutSecond = 30; // 音声認識結果が更新されない場合にクリアするまでの秒数(0以下の場合は自動クリアしない)
function vr_function() {
window.SpeechRecognition = window.SpeechRecognition || webkitSpeechRecognition;
recognition = new webkitSpeechRecognition();
recognition.lang = lang;
recognition.interimResults = true;
recognition.continuous = true;
recognition.onsoundstart = function () {
document.getElementById('status').innerHTML = "認識中...";
document.getElementById('status').className = "processing";
};
recognition.onnomatch = function () {
document.getElementById('status').innerHTML = "音声を認識できませんでした";
document.getElementById('status').className = "error";
};
recognition.onerror = function () {
document.getElementById('status').innerHTML = "エラー";
document.getElementById('status').className = "error";
if (flag_speech == 0)
vr_function();
};
recognition.onsoundend = function () {
document.getElementById('status').innerHTML = "停止中";
document.getElementById('status').className = "error";
vr_function();
};
recognition.onresult = function (event) {
var results = event.results;
for (var i = event.resultIndex; i < results.length; i++) {
if (results[i].isFinal) {
var result_transcript = results[i][0].transcript
if (lang == 'ja-JP') {
result_transcript += '。';
}
if(document.getElementById('checkbox_hiragana').checked && lang == 'ja-JP'){
document.getElementById('result_text').innerHTML = resultToHiragana(result_transcript);
}else{
document.getElementById('result_text').innerHTML = result_transcript;
}
setTimeoutForClearText();
if(document.getElementById('checkbox_timestamp').checked){
// タイムスタンプ機能
var now = new window.Date();
var Year = now.getFullYear();
var Month = (("0"+(now.getMonth()+1)).slice(-2));
var Date = ("0"+now.getDate()).slice(-2);
var Hour = ("0"+now.getHours()).slice(-2);
var Min = ("0"+now.getMinutes()).slice(-2);
var Sec = ("0"+now.getSeconds()).slice(-2);
var timestamp = Year + '-' + Month + '-' + Date + ' ' + Hour + ':' + Min + ':' + Sec + '	'
result_transcript = timestamp + result_transcript
}
document.getElementById('result_log').insertAdjacentHTML('beforeend', result_transcript+'\n');
textAreaHeightSet(document.getElementById('result_log'));
sendTextToSlack(result_transcript);
vr_function();
flag_speech = 0;
} else {
var result_transcript = results[i][0].transcript;
if(document.getElementById('checkbox_hiragana').checked && lang == 'ja-JP'){
document.getElementById('result_text').innerHTML = resultToHiragana(result_transcript);
}else{
document.getElementById('result_text').innerHTML = result_transcript;
}
flag_speech = 1;
}
}
}
flag_speech = 0;
document.getElementById('status').innerHTML = "待機中";
document.getElementById('status').className = "ready";
recognition.start();
}
function updateTextClearSecond() {
const sec = Number(document.getElementById('select_autoclear_text').value);
if ((!isNaN(sec)) && isFinite(sec) && (sec >= 0)) {
textUpdateTimeoutSecond = sec;
}
}
function clearTimeoutForClearText() {
if (textUpdateTimeoutID !== 0) {
clearTimeout(textUpdateTimeoutID);
textUpdateTimeoutID = 0;
}
}
// 変数 textUpdateTimeoutSecond に基づいてタイマーを設定する。
// タイマーの時間切れで、字幕を自動的に消去する。
// 変数の値がゼロ以下の場合はタイマーは設定されない。
// タイマーが既に動いている場合、処理タイミングは後からのもので上書きする。
function setTimeoutForClearText() {
if (textUpdateTimeoutSecond <= 0) return;
clearTimeoutForClearText();
textUpdateTimeoutID = setTimeout(
() => {
document.getElementById('result_text').innerHTML = "";
textUpdateTimeoutID = 0;
},
textUpdateTimeoutSecond * 1000);
}
// 認識結果のログのtextareaを自動変形する
// 参考: https://webparts.cman.jp/input/textarea/
function textAreaHeightSet(argObj){
// 一旦テキストエリアを小さくしてスクロールバー(縦の長さを取得)
argObj.style.height = "10px";
var wSclollHeight = parseInt(argObj.scrollHeight);
// 1行の長さを取得する
var wLineH = parseInt(argObj.style.lineHeight.replace(/px/, ''));
// 最低2行の表示エリアにする
if(wSclollHeight < (wLineH * 2)){wSclollHeight=(wLineH * 2);}
// テキストエリアの高さを設定する
argObj.style.height = wSclollHeight + "px";
}
// 認識結果をSlackに送信する
function sendTextToSlack(result_transcript){
console.log(result_transcript);
console.log(document.getElementById('checkbox_slack').checked);
if(document.getElementById('checkbox_slack').checked && document.getElementById('textbox_slack_channel').value != ''){
const endpoint = document.getElementById('textbox_slack_url').value;
console.log(endpoint);
let text = result_transcript;
if(document.getElementById('textbox_slack_user_name').value != ''){
text = `${document.getElementById('textbox_slack_user_name').value}: 「${text}」`;
}
const data = {
text: text,
as_user: true,
channel: document.getElementById('textbox_slack_channel').value,
}
const req = new XMLHttpRequest();
req.open('POST', endpoint, false);
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
req.send(`payload=${JSON.stringify(data)}`);
}
}
// 認識を手動で止める(文を区切る)
document.addEventListener('keydown',
event => {
if (event.key === 'Enter') {
if(flag_speech == 1){
recognition.stop();
}
}
});
// 認識結果のログをダウンロードする
// 参考: https://qiita.com/kerupani129/items/99fd7a768538fcd33420
function downloadLogFile(){
const a = document.createElement('a');
a.href = 'data:text/plain,' + encodeURIComponent(document.getElementById('result_log').value);
var now = new window.Date();
var Year = now.getFullYear();
var Month = (("0"+(now.getMonth()+1)).slice(-2));
var Date = ("0"+now.getDate()).slice(-2);
var Hour = ("0"+now.getHours()).slice(-2);
var Min = ("0"+now.getMinutes()).slice(-2);
var Sec = ("0"+now.getSeconds()).slice(-2);
a.download = 'log_' + Year + Month + Date + '_' + Hour + Min + Sec + '.txt';
a.click();
}
// 参考: https://blog.katsubemakito.net/html5/fullscreen
/**
* フルスクリーン開始/終了時のイベント設定
*
* @param {function} callback
*/
function eventFullScreen(callback) {
document.addEventListener("fullscreenchange", callback, false);
document.addEventListener("webkitfullscreenchange", callback, false);
document.addEventListener("mozfullscreenchange", callback, false);
document.addEventListener("MSFullscreenChange", callback, false);
}
/**
* フルスクリーンが利用できるか
*
* @return {boolean}
*/
function enabledFullScreen() {
return (
document.fullscreenEnabled || document.mozFullScreenEnabled || document.documentElement.webkitRequestFullScreen || document.msFullscreenEnabled
);
}
/**
* フルスクリーンにする
*
* @param {object} [element]
*/
function goFullScreen(element = null) {
const doc = window.document;
const docEl = (element === null) ? doc.documentElement : element;
let requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
requestFullScreen.call(docEl);
}
/**
* フルスクリーンをやめる
*/
function cancelFullScreen() {
const doc = window.document;
const cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
cancelFullScreen.call(doc);
}
/**
* フルスクリーン中のオブジェクトを返却
*/
function getFullScreenObject() {
const doc = window.document;
const objFullScreen = doc.fullscreenElement || doc.mozFullScreenElement || doc.webkitFullscreenElement || doc.msFullscreenElement;
return (objFullScreen);
}
const FullScreenBtn = document.querySelector("#FullScreenBtn"); // フルスクリーン化ボタン
const objResultText = document.querySelector("#result_text");
var font_size_windowed = parseFloat(getComputedStyle(objResultText).getPropertyValue('font-size'));
var flag_font_size_styled = 0;
window.onload = () => {
vr_function();
const video_doc = document.querySelector("#video_wrapper"); // フルスクリーンにするオブジェクト
//--------------------------------
// [event] 開始ボタンをクリック
//--------------------------------
FullScreenBtn.addEventListener("click", () => {
if (getFullScreenObject()) {
// フルスクリーンを解除
cancelFullScreen(video_doc);
}
else {
// フルスクリーンを開始
if (!enabledFullScreen()) {
alert("フルスクリーンに対応していません");
return (false);
}
goFullScreen(video_doc);
}
});
//--------------------------------
// フルスクリーンイベント
//--------------------------------
eventFullScreen(() => {
// ボタンを入れ替える
if (getFullScreenObject()) {
// フルスクリーン時に文字と画面の比率を維持
const ratio = window.parent.screen.height / document.querySelector("#result_video").clientHeight
font_size_windowed = parseFloat(getComputedStyle(objResultText).getPropertyValue('font-size'));
if(objResultText.style.fontSize){
// スライダーでフォントサイズの指定がされているかどうかを記録
flag_font_size_styled = 1;
font_size_windowed = parseFloat(getComputedStyle(objResultText).fontSize);
}
document.querySelector('#result_text').style.fontSize = parseFloat(getComputedStyle(objResultText).getPropertyValue('font-size')) * ratio +'px';
console.log("フルスクリーン開始");
} else {
// フルスクリーン時から通常画面に戻るときに文字と画面の比率を維持
if(flag_font_size_styled){
document.querySelector('#result_text').style.fontSize = document.querySelector("#value_font_size").textContent+'px';
}else{
// スライダーでフォントサイズの指定がされていなかった(デフォルトだった)場合は単にstyleのfontSizeを削除する
// 分割表示時のデフォルトCSSを活かすため
document.querySelector('#result_text').style.fontSize = '';
}
console.log("フルスクリーン終了");
}
});
initConfig();
};
// 言語切替
// 参考: https://www.google.com/intl/ja/chrome/demos/speech.html
var langs =
[['Japanese', ['ja-JP']],
['English', ['en-US', 'United States'],
['en-AU', 'Australia'],
['en-CA', 'Canada'],
['en-IN', 'India'],
['en-KE', 'Kenya'],
['en-TZ', 'Tanzania'],
['en-GH', 'Ghana'],
['en-NZ', 'New Zealand'],
['en-NG', 'Nigeria'],
['en-ZA', 'South Africa'],
['en-PH', 'Philippines'],
['en-GB', 'United Kingdom'],],
['Afrikaans', ['af-ZA']],
['አማርኛ', ['am-ET']],
['Azərbaycanca', ['az-AZ']],
['বাংলা', ['bn-BD', 'বাংলাদেশ'],
['bn-IN', 'ভারত']],
['Bahasa Indonesia',['id-ID']],
['Bahasa Melayu', ['ms-MY']],
['Català', ['ca-ES']],
['Čeština', ['cs-CZ']],
['Dansk', ['da-DK']],
['Deutsch', ['de-DE']],
['Español', ['es-AR', 'Argentina'],
['es-BO', 'Bolivia'],
['es-CL', 'Chile'],
['es-CO', 'Colombia'],
['es-CR', 'Costa Rica'],
['es-EC', 'Ecuador'],
['es-SV', 'El Salvador'],
['es-ES', 'España'],
['es-US', 'Estados Unidos'],
['es-GT', 'Guatemala'],
['es-HN', 'Honduras'],
['es-MX', 'México'],
['es-NI', 'Nicaragua'],
['es-PA', 'Panamá'],
['es-PY', 'Paraguay'],
['es-PE', 'Perú'],
['es-PR', 'Puerto Rico'],
['es-DO', 'República Dominicana'],
['es-UY', 'Uruguay'],
['es-VE', 'Venezuela']],
['Euskara', ['eu-ES']],
['Filipino', ['fil-PH']],
['Français', ['fr-FR']],
['Basa Jawa', ['jv-ID']],
['Galego', ['gl-ES']],
['ગુજરાતી', ['gu-IN']],
['Hrvatski', ['hr-HR']],
['IsiZulu', ['zu-ZA']],
['Íslenska', ['is-IS']],
['Italiano', ['it-IT', 'Italia'],
['it-CH', 'Svizzera']],
['ಕನ್ನಡ', ['kn-IN']],
['ភាសាខ្មែរ', ['km-KH']],
['Latviešu', ['lv-LV']],
['Lietuvių', ['lt-LT']],
['മലയാളം', ['ml-IN']],
['मराठी', ['mr-IN']],
['Magyar', ['hu-HU']],
['ລາວ', ['lo-LA']],
['Nederlands', ['nl-NL']],
['नेपाली भाषा', ['ne-NP']],
['Norsk bokmål', ['nb-NO']],
['Polski', ['pl-PL']],
['Português', ['pt-BR', 'Brasil'],
['pt-PT', 'Portugal']],
['Română', ['ro-RO']],
['සිංහල', ['si-LK']],
['Slovenščina', ['sl-SI']],
['Basa Sunda', ['su-ID']],
['Slovenčina', ['sk-SK']],
['Suomi', ['fi-FI']],
['Svenska', ['sv-SE']],
['Kiswahili', ['sw-TZ', 'Tanzania'],
['sw-KE', 'Kenya']],
['ქართული', ['ka-GE']],
['Հայերեն', ['hy-AM']],
['தமிழ்', ['ta-IN', 'இந்தியா'],
['ta-SG', 'சிங்கப்பூர்'],
['ta-LK', 'இலங்கை'],
['ta-MY', 'மலேசியா']],
['తెలుగు', ['te-IN']],
['Tiếng Việt', ['vi-VN']],
['Türkçe', ['tr-TR']],
['اُردُو', ['ur-PK', 'پاکستان'],
['ur-IN', 'بھارت']],
['Ελληνικά', ['el-GR']],
['български', ['bg-BG']],
['Pусский', ['ru-RU']],
['Српски', ['sr-RS']],
['Українська', ['uk-UA']],
['한국어', ['ko-KR']],
['中文', ['cmn-Hans-CN', '普通话 (中国大陆)'],
['cmn-Hans-HK', '普通话 (香港)'],
['cmn-Hant-TW', '中文 (台灣)'],
['yue-Hant-HK', '粵語 (香港)']],
['हिन्दी', ['hi-IN']],
['ภาษาไทย', ['th-TH']]];
for (var i = 0; i < langs.length; i++) {
select_language.options[i] = new Option(langs[i][0], i);
}
// デフォルトの言語を設定
select_language.selectedIndex = 0;
updateCountry();
select_dialect.selectedIndex = 0;
function updateCountry() {
for (var i = select_dialect.options.length - 1; i >= 0; i--) {
select_dialect.remove(i);
}
var list = langs[select_language.selectedIndex];
for (var i = 1; i < list.length; i++) {
select_dialect.options.add(new Option(list[i][1], list[i][0]));
}
select_dialect.style.display = list[1].length == 1 ? 'none' : 'inline';
updateLanguage()
}
function updateLanguage() {
var flag_recognition_stopped = 0;
if(recognition){
recognition.stop();
flag_recognition_stopped = 1;
}
lang = select_dialect.value;
if(flag_recognition_stopped){
vr_function();
}
var el_status_kuromoji_loading = document.getElementById('status_kuromoji_loading');
var el_checkbox_hiragana = document.getElementById('checkbox_hiragana_wrapper');
if(lang == 'ja-JP'){
el_status_kuromoji_loading.style.display = "inline-block";
el_checkbox_hiragana.style.display = "inline";
}else{
el_status_kuromoji_loading.style.display = "none";
el_checkbox_hiragana.style.display = "none";
}
}
// 結果の翻訳機能を追加
// 参考: https://pisuke-code.com/js-usage-of-google-trans-api/
function googleTranslateElementInit() {
new google.translate.TranslateElement({
layout: google.translate.TranslateElement.InlineLayout.SIMPLE
}, 'google_translate_element');
}
// フォント切替
// 参考: https://www.google.com/intl/ja/chrome/demos/speech.html
var fonts_custom =
[['Noto Sans JP', "'Noto Sans JP', sans-serif"],
['BIZ UD ゴシック(Windows 10)', "'BIZ UDゴシック', 'BIZ UDGothic', 'Noto Sans JP', sans-serif"],
['BIZ UD 明朝(Windows 10)', "'BIZ UD明朝', 'BIZ UDMincho', 'Noto Sans JP', sans-serif"],
['游ゴシック', "游ゴシック体, 'Yu Gothic', YuGothic, sans-serif"],
['メイリオ', "'メイリオ', 'Meiryo', 'Noto Sans JP', sans-serif"],
['ポップ体(Windows)', "'HGS創英角ポップ体', 'Noto Sans JP', sans-serif"],
['ゴシック体(ブラウザ標準)', "sans-serif"],
['明朝体(ブラウザ標準)', "serif"]];
for (var i = 0; i < fonts_custom.length; i++) {
select_font.options[i] = new Option(fonts_custom[i][0], i);
}
// デフォルトの言語を設定
select_font.selectedIndex = 0;
// 初期設定
const config = JSON.parse(localStorage.speech_to_text_config || '{}');
function initConfig() {
function triggerEvent(type, elem) {
const ev = document.createEvent('HTMLEvents');
ev.initEvent(type, true, true);
elem.dispatchEvent(ev);
}
['slider_font_size',
'slider_opacity',
'slider_text_shadow_stroke',
'slider_text_stroke',
'slider_line_height',
'slider_letter_spacing',
'selector_text_color',
'selector_text_shadow_color',
'selector_text_stroke_color',
'slider_text_bg_opacity',
'selector_text_bg_color',
'selector_video_bg',
].forEach(id => {
if (typeof config[id] !== 'undefined') {
const el = document.getElementById(id);
el.value = config[id];
triggerEvent('input', el);
}
});
['video_bg',
'result_video',
'text_overlay_wrapper',
'FullScreenBtn'
].forEach(id => {
if (typeof config[id] !== 'undefined') {
const el = document.getElementById(id);
if (config[id]) {
Object.keys(config[id]).forEach(key => {
if(config[id][key]){
el.classList.add(key);
}else{
el.classList.remove(key);
}
});
}
}
});
if (typeof config.position !== 'undefined') {
const el = document.getElementById(config.position);
el.checked = 'checked';
triggerEvent('input', el);
}
if (typeof config.select_font !== 'undefined') {
select_font.selectedIndex = config.select_font;
triggerEvent('change', select_font);
}
if (typeof config.checkbox_timestamp !== 'undefined') {
const el = document.getElementById('checkbox_timestamp');
el.checked = config.checkbox_timestamp;
triggerEvent('input', el);
}
if (typeof config.checkbox_hiragana !== 'undefined') {
const el = document.getElementById('checkbox_hiragana');
el.checked = config.checkbox_hiragana;
triggerEvent('input', el);
}
if (typeof config.select_autoclear_text !== 'undefined') {
const el = document.getElementById('select_autoclear_text');
selectValueIfExists(el, config.select_autoclear_text);
triggerEvent('change', el);
}
document.querySelectorAll('input.control_input').forEach(
el => el.addEventListener('input', updateConfigValue)
);
document.querySelectorAll('input[name="selector_position"]').forEach(
el => el.addEventListener('input', ev => updateConfig('position', el.id))
);
document.querySelector('#select_camera').addEventListener('change', updateConfigValue);
document.querySelector('#select_font').addEventListener('change', updateConfigValue);
document.querySelector('#checkbox_timestamp').addEventListener('input', function(e) {updateConfig(e.target.id, e.target.checked)});
document.querySelector('#checkbox_hiragana').addEventListener('input', function(e) {updateConfig(e.target.id, e.target.checked)});
document.querySelector('#checkbox_slack').addEventListener('input', function(e) {updateConfig(e.target.id, e.target.checked)});
document.querySelector('#select_autoclear_text').addEventListener('change', updateConfigValue);
}
function updateConfig(key, value) {
config[key] = value;
localStorage.speech_to_text_config = JSON.stringify(config);
}
function updateConfigClass(key, value_key, value) {
if(config[key] == undefined){
config[key] = {};
}
config[key][value_key] = value;
localStorage.speech_to_text_config = JSON.stringify(config);
}