This repository has been archived by the owner. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
actions.js
87 lines (65 loc) · 2.1 KB
/
actions.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
import { actions as serviceActions } from '../service';
import actionTypes from './action-types';
const RESULTS = {};
function getResult(reactor) {
return RESULTS[reactor.hassId];
}
function process(reactor) {
const recognition = getResult(reactor);
if (!recognition) return;
const text = recognition.finalTranscript || recognition.interimTranscript;
reactor.dispatch(actionTypes.VOICE_TRANSMITTING, { finalTranscript: text });
serviceActions.callService(reactor, 'conversation', 'process', { text }).then(
() => { reactor.dispatch(actionTypes.VOICE_DONE); },
() => { reactor.dispatch(actionTypes.VOICE_ERROR); }
);
}
export function stop(reactor) {
const result = getResult(reactor);
if (result) {
result.recognition.stop();
RESULTS[reactor.hassId] = false;
}
}
export function finish(reactor) {
process(reactor);
stop(reactor);
}
export function listen(reactor) {
const finishForReactor = finish.bind(null, reactor);
finishForReactor();
/* eslint-disable new-cap */
const recognition = new webkitSpeechRecognition();
/* eslint-enable new-cap */
RESULTS[reactor.hassId] = {
recognition,
interimTranscript: '',
finalTranscript: '',
};
recognition.interimResults = true;
recognition.onstart = () => reactor.dispatch(actionTypes.VOICE_START);
recognition.onerror = () => reactor.dispatch(actionTypes.VOICE_ERROR);
recognition.onend = finishForReactor;
recognition.onresult = (event) => {
const result = getResult(reactor);
if (!result) {
return;
}
let finalTranscript = '';
let interimTranscript = '';
for (let ind = event.resultIndex; ind < event.results.length; ind++) {
if (event.results[ind].isFinal) {
finalTranscript += event.results[ind][0].transcript;
} else {
interimTranscript += event.results[ind][0].transcript;
}
}
result.interimTranscript = interimTranscript;
result.finalTranscript += finalTranscript;
reactor.dispatch(actionTypes.VOICE_RESULT, {
interimTranscript,
finalTranscript: result.finalTranscript,
});
};
recognition.start();
}