expo-speech-recognition 0.0.1 → 0.2.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.eslintrc.js +12 -0
  2. package/.prettierignore +6 -0
  3. package/README.md +893 -0
  4. package/android/build.gradle +43 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/expo/modules/speechrecognition/DelayedFileStreamer.kt +232 -0
  7. package/android/src/main/java/expo/modules/speechrecognition/ExpoAudioRecorder.kt +217 -0
  8. package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionModule.kt +424 -0
  9. package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionOptions.kt +97 -0
  10. package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechService.kt +669 -0
  11. package/app.plugin.js +105 -0
  12. package/build/ExpoSpeechRecognitionModule.d.ts +5 -0
  13. package/build/ExpoSpeechRecognitionModule.d.ts.map +1 -0
  14. package/build/ExpoSpeechRecognitionModule.js +6 -0
  15. package/build/ExpoSpeechRecognitionModule.js.map +1 -0
  16. package/build/ExpoSpeechRecognitionModule.types.d.ts +579 -0
  17. package/build/ExpoSpeechRecognitionModule.types.d.ts.map +1 -0
  18. package/build/ExpoSpeechRecognitionModule.types.js +2 -0
  19. package/build/ExpoSpeechRecognitionModule.types.js.map +1 -0
  20. package/build/ExpoSpeechRecognitionModule.web.d.ts +12 -0
  21. package/build/ExpoSpeechRecognitionModule.web.d.ts.map +1 -0
  22. package/build/ExpoSpeechRecognitionModule.web.js +201 -0
  23. package/build/ExpoSpeechRecognitionModule.web.js.map +1 -0
  24. package/build/ExpoWebSpeechRecognition.d.ts +98 -0
  25. package/build/ExpoWebSpeechRecognition.d.ts.map +1 -0
  26. package/build/ExpoWebSpeechRecognition.js +387 -0
  27. package/build/ExpoWebSpeechRecognition.js.map +1 -0
  28. package/build/ExpoWebSpeechRecognition.web.d.ts +13 -0
  29. package/build/ExpoWebSpeechRecognition.web.d.ts.map +1 -0
  30. package/build/ExpoWebSpeechRecognition.web.js +17 -0
  31. package/build/ExpoWebSpeechRecognition.web.js.map +1 -0
  32. package/build/constants.d.ts +344 -0
  33. package/build/constants.d.ts.map +1 -0
  34. package/build/constants.js +344 -0
  35. package/build/constants.js.map +1 -0
  36. package/build/index.d.ts +26 -0
  37. package/build/index.d.ts.map +1 -0
  38. package/build/index.js +18 -0
  39. package/build/index.js.map +1 -0
  40. package/build/useSpeechRecognitionEvent.d.ts +11 -0
  41. package/build/useSpeechRecognitionEvent.d.ts.map +1 -0
  42. package/build/useSpeechRecognitionEvent.js +20 -0
  43. package/build/useSpeechRecognitionEvent.js.map +1 -0
  44. package/expo-module.config.json +9 -0
  45. package/ios/EXSpeechRecognitionPermissionRequester.swift +42 -0
  46. package/ios/ExpoSpeechRecognition.podspec +27 -0
  47. package/ios/ExpoSpeechRecognitionException.swift +84 -0
  48. package/ios/ExpoSpeechRecognitionModule.swift +480 -0
  49. package/ios/ExpoSpeechRecognizer.swift +714 -0
  50. package/ios/SpeechRecognitionOptions.swift +183 -0
  51. package/package.json +43 -6
  52. package/src/ExpoSpeechRecognitionModule.ts +16 -0
  53. package/src/ExpoSpeechRecognitionModule.types.ts +622 -0
  54. package/src/ExpoSpeechRecognitionModule.web.ts +268 -0
  55. package/src/ExpoWebSpeechRecognition.ts +512 -0
  56. package/src/ExpoWebSpeechRecognition.web.ts +17 -0
  57. package/src/constants.ts +349 -0
  58. package/src/globals.d.ts +1 -0
  59. package/src/index.ts +74 -0
  60. package/src/useSpeechRecognitionEvent.ts +30 -0
  61. package/tsconfig.json +8 -0
  62. package/index.js +0 -0
@@ -0,0 +1,424 @@
1
+ package expo.modules.speechrecognition
2
+
3
+ import android.Manifest.permission.RECORD_AUDIO
4
+ import android.annotation.SuppressLint
5
+ import android.content.ComponentName
6
+ import android.content.Context
7
+ import android.content.Intent
8
+ import android.os.Build
9
+ import android.os.Handler
10
+ import android.provider.Settings
11
+ import android.speech.ModelDownloadListener
12
+ import android.speech.RecognitionService
13
+ import android.speech.RecognitionSupport
14
+ import android.speech.RecognitionSupportCallback
15
+ import android.speech.RecognizerIntent
16
+ import android.speech.SpeechRecognizer
17
+ import android.util.Log
18
+ import androidx.annotation.RequiresApi
19
+ import expo.modules.interfaces.permissions.Permissions.askForPermissionsWithPermissionsManager
20
+ import expo.modules.interfaces.permissions.Permissions.getPermissionsWithPermissionsManager
21
+ import expo.modules.kotlin.Promise
22
+ import expo.modules.kotlin.modules.Module
23
+ import expo.modules.kotlin.modules.ModuleDefinition
24
+ import java.util.concurrent.Executors
25
+
26
+ class ExpoSpeechRecognitionModule : Module() {
27
+ private val expoSpeechService by lazy {
28
+ ExpoSpeechService(appContext.reactContext!!) { name, body ->
29
+ val nonNullBody = body ?: emptyMap()
30
+ try {
31
+ sendEvent(name, nonNullBody)
32
+ } catch (e: IllegalArgumentException) {
33
+ // "Cannot create an event emitter for the module that isn't present in the module registry."
34
+ // Likely can occur after destroying the module
35
+ Log.e("ExpoSpeechRecognitionModule", "Failed to send event: $name", e)
36
+ }
37
+ }
38
+ }
39
+
40
+ // Each module class must implement the definition function. The definition consists of components
41
+ // that describes the module's functionality and behavior.
42
+ // See https://docs.expo.dev/modules/module-api for more details about available components.
43
+ override fun definition() =
44
+ ModuleDefinition {
45
+ // Sets the name of the module that JavaScript code will use to refer to the module. Takes a
46
+ // string as an argument.
47
+ // Can be inferred from module's class name, but it's recommended to set it explicitly for
48
+ // clarity.
49
+ // The module will be accessible from `requireNativeModule('ExpoSpeechRecognition')` in
50
+ // JavaScript.
51
+ Name("ExpoSpeechRecognition")
52
+
53
+ OnDestroy {
54
+ expoSpeechService.destroy()
55
+ }
56
+
57
+ // Defines event names that the module can send to JavaScript.
58
+ Events(
59
+ // Fired when the user agent has started to capture audio.
60
+ "audiostart",
61
+ // Fired when the user agent has finished capturing audio.
62
+ "audioend",
63
+ // Fired when the speech recognition service has disconnected.
64
+ "end",
65
+ // Fired when a speech recognition error occurs.
66
+ "error",
67
+ // Fired when the speech recognition service returns a final result with no significant
68
+ // recognition. This may involve some degree of recognition, which doesn't meet or
69
+ // exceed the confidence threshold.
70
+ "nomatch",
71
+ // Fired when the speech recognition service returns a result — a word or phrase has been
72
+ // positively recognized and this has been communicated back to the app.
73
+ "result",
74
+ // Fired when any sound — recognizable speech or not — has been detected.
75
+ "soundstart",
76
+ // Fired when any sound — recognizable speech or not — has stopped being detected.
77
+ "soundend",
78
+ // Fired when sound that is recognized by the speech recognition service as speech
79
+ // has been detected.
80
+ "speechstart",
81
+ // Fired when speech recognized by the speech recognition service has stopped being
82
+ // detected.
83
+ "speechend",
84
+ // Fired when the speech recognition service has begun listening to incoming audio with
85
+ // intent to recognize grammars associated with the current SpeechRecognition
86
+ "start",
87
+ // Called when there's results (as a string array, not API compliant)
88
+ "results",
89
+ )
90
+
91
+ Function("getDefaultRecognitionService") {
92
+ val defaultRecognitionService = getDefaultVoiceRecognitionService()?.packageName ?: ""
93
+ return@Function mapOf(
94
+ "packageName" to defaultRecognitionService,
95
+ )
96
+ }
97
+
98
+ Function("getAssistantService") {
99
+ val assistantServicePackage = getDefaultAssistantService()?.packageName ?: ""
100
+ return@Function mapOf(
101
+ "packageName" to assistantServicePackage,
102
+ )
103
+ }
104
+
105
+ Function("getSpeechRecognitionServices") {
106
+ val packageManager = appContext.reactContext?.packageManager
107
+ val serviceNames = mutableListOf<String>()
108
+
109
+ if (packageManager == null) {
110
+ return@Function serviceNames
111
+ }
112
+
113
+ val services =
114
+ packageManager.queryIntentServices(
115
+ Intent(RecognitionService.SERVICE_INTERFACE),
116
+ 0,
117
+ )
118
+
119
+ for (service in services) {
120
+ serviceNames.add(service.serviceInfo.packageName)
121
+ }
122
+
123
+ return@Function serviceNames
124
+ }
125
+
126
+ AsyncFunction("requestPermissionsAsync") { promise: Promise ->
127
+ askForPermissionsWithPermissionsManager(
128
+ appContext.permissions,
129
+ promise,
130
+ RECORD_AUDIO,
131
+ )
132
+ }
133
+
134
+ AsyncFunction("getPermissionsAsync") { promise: Promise ->
135
+ getPermissionsWithPermissionsManager(
136
+ appContext.permissions,
137
+ promise,
138
+ RECORD_AUDIO,
139
+ )
140
+ }
141
+
142
+ AsyncFunction("getStateAsync") { promise: Promise ->
143
+ val state =
144
+ when (expoSpeechService.recognitionState) {
145
+ RecognitionState.INACTIVE -> "inactive"
146
+ RecognitionState.STARTING -> "starting"
147
+ RecognitionState.ACTIVE -> "recognizing"
148
+ RecognitionState.STOPPING -> "stopping"
149
+ else -> "inactive"
150
+ }
151
+
152
+ promise.resolve(state)
153
+ }
154
+
155
+ /** Start recognition with args: lang, interimResults, maxAlternatives */
156
+ Function("start") { options: SpeechRecognitionOptions ->
157
+ if (hasNotGrantedRecordPermissions()) {
158
+ sendEvent("error", mapOf("error" to "not-allowed", "message" to "Missing RECORD_AUDIO permissions."))
159
+ sendEvent("end")
160
+ return@Function
161
+ }
162
+ expoSpeechService.start(options)
163
+ }
164
+
165
+ Function("stop") {
166
+ expoSpeechService.stop()
167
+ }
168
+
169
+ Function("abort") {
170
+ sendEvent("error", mapOf("error" to "aborted", "message" to "Speech recognition aborted."))
171
+ expoSpeechService.abort()
172
+ }
173
+
174
+ AsyncFunction("getSupportedLocales") { options: GetSupportedLocaleOptions, promise: Promise ->
175
+ getSupportedLocales(options, appContext.reactContext!!, promise)
176
+ }
177
+
178
+ Function("supportsOnDeviceRecognition") {
179
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
180
+ SpeechRecognizer.isOnDeviceRecognitionAvailable(appContext.reactContext!!)
181
+ } else {
182
+ false
183
+ }
184
+ }
185
+
186
+ Function("supportsRecording") {
187
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
188
+ }
189
+
190
+ // Not necessary for Android
191
+ Function("setCategoryIOS") { _: Any ->
192
+ // Do nothing
193
+ }
194
+
195
+ Function("getAudioSessionCategoryAndOptionsIOS") {
196
+ // Just return dummy data, not necessary for Android
197
+ return@Function mapOf(
198
+ "category" to "playAndRecord",
199
+ "categoryOptions" to listOf("defaultToSpeaker", "allowBluetooth"),
200
+ "mode" to "measurement",
201
+ )
202
+ }
203
+
204
+ Function("setAudioSessionActiveIOS") { _: Any ->
205
+ // Do nothing
206
+ }
207
+
208
+ var isDownloadingModel = false
209
+
210
+ AsyncFunction("androidTriggerOfflineModelDownload") { options: TriggerOfflineModelDownloadOptions, promise: Promise ->
211
+ if (isDownloadingModel) {
212
+ promise.reject(
213
+ "download_in_progress",
214
+ "An offline model download is already in progress.",
215
+ Throwable(),
216
+ )
217
+ return@AsyncFunction
218
+ }
219
+
220
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
221
+ promise.reject(
222
+ "not_supported",
223
+ "Android version is too old to trigger offline model download.",
224
+ Throwable(),
225
+ )
226
+ return@AsyncFunction
227
+ }
228
+
229
+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
230
+ intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, options.locale)
231
+
232
+ // API 33 (Android 13) -- Trigger the model download but resolve immediately
233
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
234
+ Handler(appContext.reactContext!!.mainLooper).post {
235
+ val recognizer =
236
+ SpeechRecognizer.createOnDeviceSpeechRecognizer(appContext.reactContext!!)
237
+ recognizer.triggerModelDownload(intent)
238
+ }
239
+ promise.resolve(
240
+ mapOf(
241
+ "status" to "opened_dialog",
242
+ "message" to "Opened the model download dialog.",
243
+ ),
244
+ )
245
+ return@AsyncFunction
246
+ }
247
+
248
+ // API 34+ (Android 14+) -- Trigger the model download and listen to the progress
249
+ isDownloadingModel = true
250
+ Handler(appContext.reactContext!!.mainLooper).post {
251
+ val recognizer =
252
+ SpeechRecognizer.createOnDeviceSpeechRecognizer(appContext.reactContext!!)
253
+ recognizer.triggerModelDownload(
254
+ intent,
255
+ Executors.newSingleThreadExecutor(),
256
+ @SuppressLint("NewApi")
257
+ object : ModelDownloadListener {
258
+ override fun onProgress(p0: Int) {
259
+ // Todo: let user know the progress
260
+ }
261
+
262
+ override fun onSuccess() {
263
+ promise.resolve(
264
+ mapOf(
265
+ "status" to "download_success",
266
+ "message" to "Offline model download completed successfully.",
267
+ ),
268
+ )
269
+ isDownloadingModel = false
270
+ recognizer.destroy()
271
+ }
272
+
273
+ override fun onScheduled() {
274
+ promise.resolve(
275
+ mapOf(
276
+ "status" to "download_canceled",
277
+ "message" to "The offline model download was canceled.",
278
+ ),
279
+ )
280
+ }
281
+
282
+ override fun onError(error: Int) {
283
+ Log.e("ExpoSpeechService", "Error downloading model with code: $error")
284
+ isDownloadingModel = false
285
+ promise.reject(
286
+ "error_$error",
287
+ "Failed to download offline model download with error: $error",
288
+ Throwable(),
289
+ )
290
+ recognizer.destroy()
291
+ }
292
+ },
293
+ )
294
+ }
295
+ }
296
+ }
297
+
298
+ private fun hasNotGrantedRecordPermissions(): Boolean = appContext.permissions?.hasGrantedPermissions(RECORD_AUDIO)?.not() ?: false
299
+
300
+ private fun getDefaultAssistantService(): ComponentName? {
301
+ val contentResolver = appContext.reactContext?.contentResolver ?: return null
302
+ val defaultAssistant = Settings.Secure.getString(contentResolver, "assistant")
303
+ if (defaultAssistant.isNullOrEmpty()) {
304
+ return null
305
+ }
306
+ return ComponentName.unflattenFromString(defaultAssistant)
307
+ }
308
+
309
+ private fun getDefaultVoiceRecognitionService(): ComponentName? {
310
+ val contentResolver = appContext.reactContext?.contentResolver ?: return null
311
+ val defaultVoiceRecognitionService = Settings.Secure.getString(contentResolver, "voice_recognition_service")
312
+ if (defaultVoiceRecognitionService.isNullOrEmpty()) {
313
+ return null
314
+ }
315
+ return ComponentName.unflattenFromString(defaultVoiceRecognitionService)
316
+ }
317
+
318
+ private fun getSupportedLocales(
319
+ options: GetSupportedLocaleOptions,
320
+ appContext: Context,
321
+ promise: Promise,
322
+ ) {
323
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
324
+ promise.resolve(mutableListOf<String>())
325
+ return
326
+ }
327
+
328
+ if (options.androidRecognitionServicePackage == null && !SpeechRecognizer.isOnDeviceRecognitionAvailable(appContext)) {
329
+ promise.resolve(mutableListOf<String>())
330
+ return
331
+ }
332
+
333
+ if (options.androidRecognitionServicePackage != null && !SpeechRecognizer.isRecognitionAvailable(appContext)) {
334
+ promise.resolve(mutableListOf<String>())
335
+ return
336
+ }
337
+
338
+ var serviceComponent: ComponentName? = null
339
+ try {
340
+ if (options.androidRecognitionServicePackage != null) {
341
+ serviceComponent =
342
+ ExpoSpeechService.findComponentNameByPackageName(
343
+ appContext,
344
+ options.androidRecognitionServicePackage,
345
+ )
346
+ }
347
+ } catch (e: Exception) {
348
+ Log.e("ExpoSpeechService", "Couldn't resolve package: ${options.androidRecognitionServicePackage}")
349
+ promise.reject(
350
+ "package_not_found",
351
+ "Failed to retrieve recognition service package",
352
+ e,
353
+ )
354
+ return
355
+ }
356
+
357
+ var didResolve = false
358
+
359
+ // Speech Recognizer can only be ran on main thread
360
+ Handler(appContext.mainLooper).post {
361
+ val recognizer =
362
+ if (serviceComponent != null) {
363
+ SpeechRecognizer.createSpeechRecognizer(
364
+ appContext,
365
+ serviceComponent,
366
+ )
367
+ } else {
368
+ SpeechRecognizer.createOnDeviceSpeechRecognizer(appContext)
369
+ }
370
+
371
+ val recognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
372
+
373
+ recognizer?.checkRecognitionSupport(
374
+ recognizerIntent,
375
+ Executors.newSingleThreadExecutor(),
376
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
377
+ object : RecognitionSupportCallback {
378
+ override fun onSupportResult(recognitionSupport: RecognitionSupport) {
379
+ Log.d("ExpoSpeechService", "onSupportResult() called with recognitionSupport: $recognitionSupport")
380
+ // Seems to get called twice when using `createSpeechRecognizer()`
381
+ if (didResolve) {
382
+ return
383
+ }
384
+ didResolve = true
385
+ // These languages are supported but need to be downloaded before use.
386
+ val installedLocales = recognitionSupport.installedOnDeviceLanguages
387
+
388
+ val locales =
389
+ recognitionSupport.supportedOnDeviceLanguages
390
+ .union(installedLocales)
391
+ .union(recognitionSupport.onlineLanguages)
392
+ .sorted()
393
+ promise.resolve(
394
+ mapOf(
395
+ "locales" to locales,
396
+ "installedLocales" to installedLocales,
397
+ ),
398
+ )
399
+ recognizer.destroy()
400
+ }
401
+
402
+ override fun onError(error: Int) {
403
+ Log.e("ExpoSpeechService", "getSupportedLocales.onError() called with error code: $error")
404
+ // This is a workaround for when both the onSupportResult and onError callbacks are called
405
+ // This occurs when providing some packages such as com.google.android.tts
406
+ // com.samsung.android.bixby.agent usually errors though
407
+ Handler(appContext.mainLooper).postDelayed({
408
+ if (didResolve) {
409
+ return@postDelayed
410
+ }
411
+ promise.reject(
412
+ "error_$error",
413
+ "Failed to retrieve supported locales with error: $error",
414
+ Throwable(),
415
+ )
416
+ }, 50)
417
+
418
+ recognizer.destroy()
419
+ }
420
+ },
421
+ )
422
+ }
423
+ }
424
+ }
@@ -0,0 +1,97 @@
1
+ package expo.modules.speechrecognition
2
+
3
+ import android.media.AudioFormat
4
+ import android.speech.RecognizerIntent
5
+ import expo.modules.kotlin.records.Field
6
+ import expo.modules.kotlin.records.Record
7
+
8
+ class SpeechRecognitionOptions : Record {
9
+ @Field
10
+ val interimResults: Boolean? = false
11
+
12
+ @Field
13
+ val lang: String = "en-US"
14
+
15
+ @Field
16
+ val continuous: Boolean? = false
17
+
18
+ @Field
19
+ val maxAlternatives: Int? = 5
20
+
21
+ @Field
22
+ var contextualStrings: List<String>? = null
23
+
24
+ @Field
25
+ var requiresOnDeviceRecognition: Boolean? = false
26
+
27
+ @Field
28
+ var addsPunctuation: Boolean? = false
29
+
30
+ @Field
31
+ var androidIntentOptions: Map<String, Any>? = null
32
+
33
+ @Field
34
+ val androidRecognitionServicePackage: String? = null
35
+
36
+ /**
37
+ * Provide an audio source (e.g. microphone or file) to use for speech recognition.
38
+ */
39
+ @Field
40
+ val audioSource: AudioSourceOptions? = null
41
+
42
+ @Field
43
+ val recordingOptions: RecordingOptions? = null
44
+
45
+ @Field
46
+ val androidIntent: String? = RecognizerIntent.ACTION_RECOGNIZE_SPEECH
47
+
48
+ @Field
49
+ val iosTaskHint: String? = null
50
+
51
+ @Field
52
+ val iosCategory: Map<String, Any>? = null
53
+ }
54
+
55
+ class RecordingOptions : Record {
56
+ @Field
57
+ val persist: Boolean = false
58
+
59
+ @Field
60
+ val outputDirectory: String? = null
61
+
62
+ @Field
63
+ val outputFileName: String? = null
64
+
65
+ @Field
66
+ val outputSampleRate: Int? = null
67
+
68
+ @Field
69
+ val outputEncoding: String? = null
70
+ }
71
+
72
+ class AudioSourceOptions : Record {
73
+ @Field
74
+ val uri: String = ""
75
+
76
+ @Field
77
+ val audioEncoding: Int? = AudioFormat.ENCODING_PCM_16BIT
78
+
79
+ @Field
80
+ val sampleRate: Int? = 16000
81
+
82
+ @Field
83
+ val audioChannels: Int? = 1
84
+
85
+ @Field
86
+ val chunkDelayMillis: Long? = null
87
+ }
88
+
89
+ class GetSupportedLocaleOptions : Record {
90
+ @Field
91
+ val androidRecognitionServicePackage: String? = null
92
+ }
93
+
94
+ class TriggerOfflineModelDownloadOptions : Record {
95
+ @Field
96
+ val locale: String = "en-US"
97
+ }