-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathExpoSpeechRecognitionModule.web.ts
264 lines (248 loc) · 8.33 KB
/
ExpoSpeechRecognitionModule.web.ts
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
import type { PermissionResponse } from "expo-modules-core";
import type {
ExpoSpeechRecognitionModuleType,
ExpoSpeechRecognitionNativeEventMap,
} from "./ExpoSpeechRecognitionModule.types";
let _speechRecognitionRef: SpeechRecognition | null = null;
// It loads the native module object from the JSI or falls back to
// the bridge module (from NativeModulesProxy) if the remote debugger is on.
export const ExpoSpeechRecognitionModule: ExpoSpeechRecognitionModuleType = {
start: (options) => {
const SpeechRecognitionClass =
typeof webkitSpeechRecognition !== "undefined"
? webkitSpeechRecognition
: SpeechRecognition;
_speechRecognitionRef = new SpeechRecognitionClass();
_speechRecognitionRef.lang = options.lang ?? "en-US";
_speechRecognitionRef.interimResults = options.interimResults ?? false;
_speechRecognitionRef.maxAlternatives = options.maxAlternatives ?? 1;
_speechRecognitionRef.continuous = options.continuous ?? false;
// Re-subscribe to events so that we don't lose them
// This covers the case where the user has already subscribed to an event prior to calling `start()`
ExpoSpeechRecognitionModuleEmitter._nativeListeners.forEach(
(listeners, eventName) => {
for (const listener of listeners) {
// May already be subscribed
_speechRecognitionRef?.removeEventListener(eventName, listener);
_speechRecognitionRef?.addEventListener(eventName, listener);
}
},
);
// Start the speech recognition!
_speechRecognitionRef.start();
},
getStateAsync: () => {
console.warn(
"getStateAsync is not supported on web. Returning 'inactive'.",
);
return Promise.resolve("inactive");
},
stop: () => _speechRecognitionRef?.stop(),
abort: () => _speechRecognitionRef?.abort(),
requestPermissionsAsync: () => {
return Promise.resolve({
granted: true,
canAskAgain: false,
expires: "never",
status: "granted",
} as PermissionResponse);
},
getPermissionsAsync: () => {
console.warn(
"getPermissionsAsync is not supported on web. Returning a denied permission response.",
);
return Promise.resolve({
granted: false,
canAskAgain: false,
expires: "never",
status: "denied",
} as PermissionResponse);
},
getSupportedLocales: async () => {
console.warn(
"getSupportedLocales is not supported on web. Returning an empty array.",
);
return {
locales: [] as string[],
installedLocales: [] as string[],
};
},
addListener: () => {
console.warn(
"addListener is not supported. Use ExpoSpeechRecognitionModuleEmitter(eventName, listener) instead.",
);
},
removeListeners: () => {
console.warn(
"removeListeners is not supported. Use ExpoSpeechRecognitionModuleEmitter.removeListener(eventName, listener) instead.",
);
},
getSpeechRecognitionServices: () => {
return [] as string[];
},
getDefaultRecognitionService: () => {
return {
packageName: "",
};
},
getAssistantService: () => {
return {
packageName: "",
};
},
supportsOnDeviceRecognition: () => {
return false;
},
supportsRecording: () => {
return false;
},
androidTriggerOfflineModelDownload: () => {
console.warn(
"androidTriggerOfflineModelDownload is not supported on web. Returning false.",
);
return Promise.resolve({
status: "opened_dialog",
message: "Offline model download is not supported on web.",
});
},
setCategoryIOS: () => {
console.warn("setCategoryIOS is not supported on web.");
},
getAudioSessionCategoryAndOptionsIOS: () => {
console.warn(
"getAudioSessionCategoryAndOptionsIOS is not supported on web.",
);
return {
category: "playAndRecord",
categoryOptions: ["defaultToSpeaker", "allowBluetooth"],
mode: "measurement",
};
},
setAudioSessionActiveIOS: () => {
console.warn("setAudioSessionActiveIOS is not supported on web.");
},
isRecognitionAvailable: () => {
const hasSpeechRecognitionAPI =
typeof webkitSpeechRecognition !== "undefined" ||
typeof SpeechRecognition !== "undefined";
return hasSpeechRecognitionAPI;
},
};
/**
* Convert the web SpeechRecognitionEventMap to the native event map for compatibility
*/
const webToNativeEventMap: {
[K in keyof SpeechRecognitionEventMap]: (
ev: SpeechRecognitionEventMap[K],
) => ExpoSpeechRecognitionNativeEventMap[K];
} = {
audioend: (ev) => ({ uri: null }),
audiostart: (ev) => ({ uri: null }),
end: (ev) => null,
error: (ev) => ({ error: ev.error, message: ev.message }),
nomatch: (ev) => null,
result: (ev) => {
const nativeResults: ExpoSpeechRecognitionNativeEventMap["result"]["results"] =
[];
for (let i = 0; i < ev.results[ev.resultIndex].length; i++) {
const result = ev.results[ev.resultIndex][i];
nativeResults.push({
transcript: result.transcript,
confidence: result.confidence,
segments: [],
});
}
return {
isFinal: Boolean(ev.results[ev.resultIndex]?.isFinal),
results: nativeResults,
};
},
soundstart: (ev) => null,
speechend: (ev) => null,
speechstart: (ev) => null,
start: (ev) => null,
soundend: (ev) => null,
};
export const ExpoSpeechRecognitionModuleEmitter = {
_nativeListeners: new Map() as Map<string, Set<(event: any) => void>>,
_clientListeners: new Map() as Map<
// Original listener
(event: any) => void,
// Native listener
(event: any) => void
>,
addListener<T extends keyof SpeechRecognitionEventMap>(
eventName: T,
listener: (ev: ExpoSpeechRecognitionNativeEventMap[T]) => void,
) {
// Convert the web event to the native event
const nativeListener = (ev: SpeechRecognitionEventMap[T]) => {
const eventPayload = webToNativeEventMap[eventName]?.(ev);
listener(eventPayload);
};
_speechRecognitionRef?.addEventListener(eventName, nativeListener);
if (!ExpoSpeechRecognitionModuleEmitter._nativeListeners.has(eventName)) {
ExpoSpeechRecognitionModuleEmitter._nativeListeners.set(
eventName,
new Set(),
);
}
// Add the original listener to the enhanced listeners
ExpoSpeechRecognitionModuleEmitter._nativeListeners
.get(eventName)
?.add(nativeListener);
// Map the original listener to the enhanced listener
ExpoSpeechRecognitionModuleEmitter._clientListeners.set(
listener,
nativeListener,
);
return {
remove: () => {
_speechRecognitionRef?.removeEventListener(eventName, nativeListener);
ExpoSpeechRecognitionModuleEmitter._nativeListeners
.get(eventName)
?.delete(nativeListener);
ExpoSpeechRecognitionModuleEmitter._clientListeners.delete(listener);
},
};
},
removeListener: (eventName: string, listener: (event: any) => void) => {
const resolvedListener =
ExpoSpeechRecognitionModuleEmitter._clientListeners.get(listener) ??
listener;
_speechRecognitionRef?.removeEventListener(eventName, resolvedListener);
if (ExpoSpeechRecognitionModuleEmitter._nativeListeners.has(eventName)) {
ExpoSpeechRecognitionModuleEmitter._nativeListeners
.get(eventName)
?.delete(listener);
}
ExpoSpeechRecognitionModuleEmitter._clientListeners.delete(listener);
},
removeAllListeners: (eventName: string) => {
// Go through _listeners and remove all listeners for this event
if (ExpoSpeechRecognitionModuleEmitter._nativeListeners.has(eventName)) {
const nativeListeners =
ExpoSpeechRecognitionModuleEmitter._nativeListeners.get(eventName);
if (!nativeListeners) {
return;
}
// Remove the enhanced listeners
for (const [
listener,
nativeListener,
] of ExpoSpeechRecognitionModuleEmitter._clientListeners) {
// if nativeListener in listeners, remove it
if (nativeListeners.has(nativeListener)) {
// Remove the enhanced listener
ExpoSpeechRecognitionModuleEmitter._clientListeners.delete(listener);
}
}
// Remove the native listeners
for (const listener of nativeListeners) {
ExpoSpeechRecognitionModuleEmitter.removeListener(eventName, listener);
}
// Clean up
ExpoSpeechRecognitionModuleEmitter._nativeListeners.delete(eventName);
}
},
};