Skip to content

Commit b1763d5

Browse files
committed
20: add my JavaScript code
Signed-off-by: Soshi Katsuta <soshi.katsuta@gmail.com>
1 parent 38dd178 commit b1763d5

File tree

3 files changed

+1952
-5
lines changed

3 files changed

+1952
-5
lines changed

20 - Speech Detection/index-START.html

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,7 @@
99
<div class="words" contenteditable>
1010
</div>
1111

12-
<script>
13-
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
14-
15-
16-
</script>
12+
<script src="script.js"></script>
1713

1814

1915
<style>

20 - Speech Detection/script.js

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
'use strict';
2+
3+
class Notifier {
4+
constructor() {
5+
this.handlers = [];
6+
}
7+
8+
addHandler(handler) {
9+
this.handlers.push(handler);
10+
}
11+
12+
notify() {
13+
this.handlers.forEach(handler => handler());
14+
}
15+
}
16+
17+
class Recognition {
18+
constructor(notifier) {
19+
this.notifier = notifier;
20+
this._text = '';
21+
}
22+
23+
get text() {
24+
return this._text;
25+
}
26+
27+
set text(transcript) {
28+
this._text = transcript;
29+
this.notifyUpdate();
30+
}
31+
32+
addHandler(handler) {
33+
this.notifier.addHandler(handler);
34+
}
35+
36+
notifyUpdate() {
37+
this.notifier.notify();
38+
}
39+
}
40+
41+
class ViewModel {
42+
constructor(words) {
43+
this.words = words;
44+
this.currentParagraph = document.createElement('p');
45+
this.words.appendChild(this.currentParagraph);
46+
this.recognition = new Recognition(new Notifier());
47+
48+
this.recognition.addHandler(() => {
49+
this.text = this.recognition.text;
50+
});
51+
this.recognition.notifyUpdate();
52+
}
53+
54+
recognize(ev) {
55+
const transcript = Array.from(ev.results)
56+
.map(result => result[0].transcript)
57+
.join('');
58+
59+
this.recognition.text = transcript;
60+
this.currentParagraph.textContent = this.text;
61+
62+
if (!ev.results[0].isFinal) { return; }
63+
64+
this.currentParagraph = document.createElement('p');
65+
this.words.appendChild(this.currentParagraph);
66+
}
67+
}
68+
69+
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
70+
71+
const recognition = new SpeechRecognition();
72+
recognition.interimResults = true;
73+
const words = document.querySelector('.words');
74+
const vm = new ViewModel(words);
75+
76+
recognition.addEventListener('result', ev => vm.recognize(ev));
77+
recognition.addEventListener('end', recognition.start);
78+
recognition.start();

0 commit comments

Comments
 (0)