-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
90 lines (75 loc) · 1.84 KB
/
index.js
File metadata and controls
90 lines (75 loc) · 1.84 KB
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
import { h, Component } from 'preact';
import { forEachObjIndexed } from 'ramda';
class SpeechBase extends Component {
onVoice(text) {
try {
forEachObjIndexed(
(value, key) => {
if (text.match(key) != null)
this.props.resolver[key](text, this.props);
},
this.props.resolver
);
}
catch (error) {
console.log(error, text);
}
}
onSpeechEnd() {
console.log(
'You were quiet for a while so voice recognition turned itself off.'
);
}
onEnd() {
if (this.state.active) {
console.log('restarting recognition');
this.recognition.start();
}
}
onError(event) {
if (event.error == 'no-speech')
console.log('no speech detected');
}
onResult(event) {
let current = event.resultIndex;
let transcript = event.results[current][0].transcript;
let mobileRepeatBug = (current == 1 && transcript == event.results[0][0].transcript);
if (!mobileRepeatBug) {
console.log(transcript);
this.onVoice(transcript);
}
}
trigger() {
this.setState({ active: !this.state.active });
if (this.state.active)
this.recognition.start();
else
this.recognition.stop();
}
constructor() {
super();
this.state = { active: false };
}
componentDidMount() {
if (typeof window !== 'undefined') {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
this.recognition = new SpeechRecognition();
this.recognition.continuous = true;
this.recognition.onspeechend = this.onSpeechEnd;
this.recognition.onend = this.onEnd;
this.recognition.onerror = this.onError;
this.recognition.onresult = this.onResult;
if (this.state.active)
this.recognition.start();
}
}
render({ style }) {
return (
<a style={style} onClick={this.trigger}>
Speech recognition
{ this.state.active ? ' active' : ' disabled' }
</a>
);
}
}
export default SpeechBase;