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,669 @@
1
+ package expo.modules.speechrecognition
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.content.ComponentName
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import android.content.pm.ResolveInfo
8
+ import android.media.AudioFormat
9
+ import android.os.Build
10
+ import android.os.Bundle
11
+ import android.os.Handler
12
+ import android.os.Looper
13
+ import android.speech.RecognitionListener
14
+ import android.speech.RecognitionPart
15
+ import android.speech.RecognitionService
16
+ import android.speech.RecognizerIntent
17
+ import android.speech.SpeechRecognizer
18
+ import android.util.Log
19
+ import java.io.File
20
+ import java.net.URI
21
+ import java.util.Locale
22
+
23
+ data class SpeechRecognitionErrorEvent(
24
+ val error: String,
25
+ val message: String,
26
+ )
27
+
28
+ enum class RecognitionState {
29
+ INACTIVE, // Represents the inactive state
30
+ STARTING,
31
+ ACTIVE, // Represents the active state
32
+ STOPPING,
33
+ ERROR, // Inactive, but error occurred. Prevent dispatching any additional events until start() is called
34
+ // Add more states as needed
35
+ }
36
+
37
+ /**
38
+ * Represents the state of the sound for tracking sound events (soundstart, soundend)
39
+ */
40
+ enum class SoundState {
41
+ INACTIVE,
42
+ ACTIVE,
43
+ SILENT,
44
+ }
45
+
46
+ class ExpoSpeechService(
47
+ private val reactContext: Context,
48
+ private var sendEvent: (name: String, body: Map<String, Any?>?) -> Unit,
49
+ ) : RecognitionListener {
50
+ private var speech: SpeechRecognizer? = null
51
+ private val mainHandler = Handler(Looper.getMainLooper())
52
+ /** Audio recorder for persisting audio */
53
+ private var audioRecorder: ExpoAudioRecorder? = null
54
+ /** File streamer for file-based recognition */
55
+ private var delayedFileStreamer: DelayedFileStreamer? = null
56
+ private var soundState = SoundState.INACTIVE
57
+
58
+ var recognitionState = RecognitionState.INACTIVE
59
+
60
+ companion object {
61
+ @SuppressLint("QueryPermissionsNeeded")
62
+ fun findComponentNameByPackageName(
63
+ context: Context,
64
+ packageName: String,
65
+ ): ComponentName {
66
+ val packageManager = context.packageManager
67
+ val services: List<ResolveInfo> = packageManager.queryIntentServices(Intent(RecognitionService.SERVICE_INTERFACE), 0)
68
+
69
+ for (service in services) {
70
+ if (service.serviceInfo.packageName == packageName) {
71
+ Log.d("ExpoSpeechService", "Found service for package $packageName: ${service.serviceInfo.name}")
72
+ return ComponentName(service.serviceInfo.packageName, service.serviceInfo.name)
73
+ }
74
+ }
75
+
76
+ throw Exception("No service found for package $packageName")
77
+ }
78
+ }
79
+
80
+ private fun log(message: String) {
81
+ Log.d("ExpoSpeechService", message)
82
+ }
83
+
84
+ private fun createSpeechRecognizer(options: SpeechRecognitionOptions): SpeechRecognizer? {
85
+ val value =
86
+ when {
87
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && options.requiresOnDeviceRecognition == true -> {
88
+ SpeechRecognizer.createOnDeviceSpeechRecognizer(reactContext)
89
+ }
90
+ // Custom service package, e.g. "com.google.android.googlequicksearchbox"
91
+ // Note: requires to be listed in AppManifest <queries> for this intent (android.speech.RecognitionService)
92
+ // Otherwise it will throw "Bind to system recognition service failed with error 10"
93
+ options.androidRecognitionServicePackage != null -> {
94
+ SpeechRecognizer.createSpeechRecognizer(
95
+ reactContext,
96
+ findComponentNameByPackageName(reactContext, options.androidRecognitionServicePackage),
97
+ )
98
+ }
99
+ else -> {
100
+ SpeechRecognizer.createSpeechRecognizer(reactContext)
101
+ }
102
+ }
103
+
104
+ return value
105
+ }
106
+
107
+ /** Starts speech recognition */
108
+ fun start(options: SpeechRecognitionOptions) {
109
+ mainHandler.post {
110
+ log("Start recognition.")
111
+
112
+ // Destroy any previous SpeechRecognizer / audio recorder
113
+ speech?.destroy()
114
+ audioRecorder?.stop()
115
+ audioRecorder = null
116
+ delayedFileStreamer?.close()
117
+ delayedFileStreamer = null
118
+ recognitionState = RecognitionState.STARTING
119
+ soundState = SoundState.INACTIVE
120
+ try {
121
+ val intent = createSpeechIntent(options)
122
+ speech = createSpeechRecognizer(options)
123
+
124
+ // Start the audio recorder
125
+ audioRecorder?.start()
126
+
127
+ // Start listening
128
+ speech?.setRecognitionListener(this)
129
+ speech?.startListening(intent)
130
+
131
+ delayedFileStreamer?.startStreaming()
132
+
133
+ sendEvent(
134
+ "audiostart",
135
+ mapOf(
136
+ "uri" to audioRecorder?.outputFileUri,
137
+ ),
138
+ )
139
+ } catch (e: Exception) {
140
+ val errorMessage =
141
+ when {
142
+ e.localizedMessage != null -> e.localizedMessage
143
+ e.message != null -> e.message
144
+ else -> "Unknown error"
145
+ }
146
+ e.printStackTrace()
147
+ log("Failed to create Speech Recognizer with error: $errorMessage")
148
+ sendEvent("error", mapOf("error" to "audio-capture", "message" to errorMessage))
149
+ teardownAndEnd()
150
+ }
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Stops the audio recorder and sends the recorded audio file path to the app.
156
+ */
157
+ private fun stopRecording() {
158
+ audioRecorder?.stop()
159
+ if (audioRecorder?.outputFile != null) {
160
+ val uri = audioRecorder?.outputFile?.absolutePath?.let { "file://$it" }
161
+ sendEvent(
162
+ "audioend",
163
+ mapOf(
164
+ "uri" to uri,
165
+ ),
166
+ )
167
+ } else {
168
+ sendEvent(
169
+ "audioend",
170
+ mapOf(
171
+ "uri" to null,
172
+ ),
173
+ )
174
+ }
175
+ audioRecorder = null
176
+ }
177
+
178
+ /**
179
+ * Stops the speech recognizer.
180
+ * Attempts to emit a final result if the speech recognizer is still running.
181
+ */
182
+ fun stop() {
183
+ mainHandler.post {
184
+ recognitionState = RecognitionState.STOPPING
185
+ try {
186
+ speech?.stopListening()
187
+ } catch (e: Exception) {
188
+ // do nothing
189
+ }
190
+ }
191
+ // Wait for the onResults() / onError() handlers to be called
192
+ // This is to ensure that the final result is emitted and the end event is sent
193
+ }
194
+
195
+ /**
196
+ * Immediately cancels the current speech recognition task.
197
+ * This is different from `stop` in that the recognition task is immediately cancelled and no
198
+ * final result is emitted.
199
+ */
200
+ fun abort() {
201
+ teardownAndEnd()
202
+ }
203
+
204
+ /**
205
+ * Destroys the speech service and stops all audio recording
206
+ */
207
+ fun destroy() {
208
+ // Overwrite sendEvent to prevent sending events after destroy
209
+ sendEvent = { _, _ -> }
210
+ teardownAndEnd()
211
+ }
212
+
213
+ /**
214
+ * Stops speech recognition, recording and updates state
215
+ */
216
+ private fun teardownAndEnd(state: RecognitionState = RecognitionState.INACTIVE) {
217
+ recognitionState = RecognitionState.STOPPING
218
+ mainHandler.post {
219
+ try {
220
+ speech?.cancel()
221
+ } catch (e: Exception) {
222
+ // do nothing
223
+ }
224
+ speech?.destroy()
225
+ stopRecording()
226
+ soundState = SoundState.INACTIVE
227
+ sendEvent("end", null)
228
+ recognitionState = state
229
+ delayedFileStreamer?.close()
230
+ delayedFileStreamer = null
231
+ }
232
+ }
233
+
234
+ private fun createSpeechIntent(options: SpeechRecognitionOptions): Intent {
235
+ val action = options.androidIntent ?: RecognizerIntent.ACTION_RECOGNIZE_SPEECH
236
+ val intent = Intent(action)
237
+
238
+ // Optional boolean to indicate whether partial results should be returned by
239
+ // the recognizer as the user speaks (default is false).
240
+ // The server may ignore a request for partial results in some or all cases.
241
+ intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, options.interimResults)
242
+
243
+ // Allow users to override the language mode
244
+ if (options.androidIntentOptions?.containsKey("EXTRA_LANGUAGE_MODEL") != true) {
245
+ intent.putExtra(
246
+ RecognizerIntent.EXTRA_LANGUAGE_MODEL,
247
+ RecognizerIntent.LANGUAGE_MODEL_FREE_FORM,
248
+ )
249
+ }
250
+
251
+ // Feature: Confidence levels on transcript words (i.e. `results[x].segments` on the "result" event)
252
+ if (action == RecognizerIntent.ACTION_RECOGNIZE_SPEECH &&
253
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
254
+ ) {
255
+ intent.putExtra(RecognizerIntent.EXTRA_REQUEST_WORD_CONFIDENCE, true)
256
+ intent.putExtra(RecognizerIntent.EXTRA_REQUEST_WORD_TIMING, true)
257
+ }
258
+
259
+ // Set up audio recording & sink to recognizer/file
260
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && options.audioSource == null) {
261
+ // Feature: Stream microphone input to SpeechRecognition so the user can access the audio blob
262
+ if (options.recordingOptions?.persist == true) {
263
+ audioRecorder = ExpoAudioRecorder(reactContext, resolveFilePathFromConfig(options.recordingOptions))
264
+ } else if (options.continuous == true) {
265
+ // Feature: Continuous transcription from microphone using `RecognizerIntent.EXTRA_AUDIO_SOURCE`
266
+ // This also has the side effect of not playing the "beep" sound when starting and stopping recognition
267
+ audioRecorder = ExpoAudioRecorder(reactContext, null)
268
+ }
269
+
270
+ // Set common intent extras if audioRecorder is initialized
271
+ audioRecorder?.let {
272
+ intent.putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE, it.recordingParcel)
273
+ intent.putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE_CHANNEL_COUNT, 1)
274
+ intent.putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE_ENCODING, it.audioFormat)
275
+ intent.putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE_SAMPLING_RATE, it.sampleRateInHz)
276
+
277
+ if (options.continuous == true) {
278
+ intent.putExtra(
279
+ RecognizerIntent.EXTRA_SEGMENTED_SESSION,
280
+ RecognizerIntent.EXTRA_AUDIO_SOURCE,
281
+ )
282
+ } else {
283
+ // Non-continuous mode while file recording (Android 13 and above)
284
+ intent.putExtra(
285
+ RecognizerIntent.EXTRA_SEGMENTED_SESSION,
286
+ RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS,
287
+ )
288
+ intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 2000)
289
+ intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 1000)
290
+ intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, 2000)
291
+ }
292
+ }
293
+ } else if (options.continuous == true && options.audioSource == null) {
294
+ // Below Android 13 we can only use `EXTRA_SPEECH_INPUT_...` extras for continuous transcription
295
+ intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 600000)
296
+ intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 600000)
297
+ intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, 600000)
298
+ log("Continuous transcription opted in (older platforms)")
299
+ }
300
+
301
+ // Feature: Transcribe audio from a local or remote file
302
+ if (options.audioSource?.uri != null) {
303
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
304
+ throw Exception("Audio source is only supported on Android 13 and above")
305
+ }
306
+
307
+ log("Transcribing audio from local file: ${options.audioSource.uri}")
308
+ val file = resolveSourceUri(options.audioSource.uri)
309
+
310
+ // The file should exist, otherwise throw an error
311
+ if (!file.exists()) {
312
+ throw Exception("File not found: ${file.absolutePath}")
313
+ }
314
+ if (!file.canRead()) {
315
+ throw Exception("File cannot be read: ${file.absolutePath}")
316
+ }
317
+
318
+ val chunkDelayMillis =
319
+ when {
320
+ options.audioSource.chunkDelayMillis != null -> options.audioSource.chunkDelayMillis
321
+ options.requiresOnDeviceRecognition == true -> 15L // On-device recognition
322
+ else -> 50L // Network-based recognition
323
+ }
324
+
325
+ delayedFileStreamer = DelayedFileStreamer(file, chunkDelayMillis)
326
+
327
+ delayedFileStreamer?.let {
328
+ val descriptor = it.getParcel()
329
+ intent.putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE, descriptor)
330
+
331
+ intent.putExtra(
332
+ RecognizerIntent.EXTRA_AUDIO_SOURCE_ENCODING,
333
+ options.audioSource.audioEncoding ?: AudioFormat.ENCODING_PCM_16BIT,
334
+ )
335
+ intent.putExtra(
336
+ RecognizerIntent.EXTRA_AUDIO_SOURCE_SAMPLING_RATE,
337
+ options.audioSource.sampleRate ?: 16000,
338
+ )
339
+ intent.putExtra(
340
+ RecognizerIntent.EXTRA_AUDIO_SOURCE_CHANNEL_COUNT,
341
+ options.audioSource.audioChannels ?: 1,
342
+ )
343
+ intent.putExtra(
344
+ RecognizerIntent.EXTRA_SEGMENTED_SESSION,
345
+ RecognizerIntent.EXTRA_AUDIO_SOURCE,
346
+ )
347
+ }
348
+ }
349
+
350
+ val contextualStrings = options.contextualStrings
351
+ if (!contextualStrings.isNullOrEmpty() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
352
+ // Optional list of strings, towards which the recognizer should bias the recognition results.
353
+ // These are separate from the device context.
354
+ val strings = ArrayList(contextualStrings)
355
+ log("biasing strings: ${strings.joinToString(", ")}")
356
+ intent.putExtra(
357
+ RecognizerIntent.EXTRA_BIASING_STRINGS,
358
+ // List<String> -> ArrayList<java.lang.String>
359
+ ArrayList(contextualStrings),
360
+ )
361
+ }
362
+
363
+ if (options.addsPunctuation == true && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
364
+ intent.putExtra(RecognizerIntent.EXTRA_ENABLE_FORMATTING, RecognizerIntent.FORMATTING_OPTIMIZE_QUALITY)
365
+ }
366
+
367
+ // Offline recognition
368
+ // to be used with ACTION_RECOGNIZE_SPEECH, ACTION_VOICE_SEARCH_HANDS_FREE, ACTION_WEB_SEARCH
369
+ if (options.requiresOnDeviceRecognition == true) {
370
+ intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true)
371
+ }
372
+
373
+ // Optional limit on the maximum number of results to return.
374
+ // If omitted the recognizer will choose how many results to return. Must be an integer.
375
+ intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, options.maxAlternatives)
376
+
377
+ val language = options.lang.takeIf { it.isNotEmpty() } ?: Locale.getDefault().toString()
378
+ intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language)
379
+
380
+ log("androidIntentOptions: ${options.androidIntentOptions}")
381
+
382
+ // Add any additional intent extras provided by the user
383
+ options.androidIntentOptions?.forEach { (key, value) ->
384
+ // Use reflection to set the extra
385
+ // i.e. RecognizerIntent[key
386
+ val field = RecognizerIntent::class.java.getDeclaredField(key)
387
+ val fieldValue = field.get(null) as? String
388
+
389
+ log("Resolved key $key -> $fieldValue with value: $value (${value.javaClass.name})")
390
+ when (value) {
391
+ is Boolean -> intent.putExtra(fieldValue, value)
392
+ is Int -> intent.putExtra(fieldValue, value)
393
+ is String -> intent.putExtra(fieldValue, value)
394
+ is List<*> -> {
395
+ if (value.all { it is String }) {
396
+ intent.putExtra(fieldValue, value.filterIsInstance<String>().toTypedArray())
397
+ }
398
+ }
399
+ is Double -> intent.putExtra(fieldValue, value.toInt())
400
+ else -> throw IllegalArgumentException("Unsupported type for androidIntentOptions.$key: ${value.javaClass.name}")
401
+ }
402
+ }
403
+
404
+ return intent
405
+ }
406
+
407
+ private fun resolveFilePathFromConfig(recordingOptions: RecordingOptions): String {
408
+ // Normalize the file directory
409
+ val fileDirectory =
410
+ (recordingOptions.outputDirectory ?: reactContext.cacheDir.absolutePath)
411
+ .removePrefix("file://")
412
+ .trimEnd('/')
413
+
414
+ val filePath =
415
+ recordingOptions.outputFileName?.let { fileName ->
416
+ "$fileDirectory/$fileName"
417
+ } ?: run {
418
+ val timestamp = System.currentTimeMillis().toString()
419
+ "$fileDirectory/recording_$timestamp.wav"
420
+ }
421
+ return filePath
422
+ }
423
+
424
+ /**
425
+ * Resolves the source URI to a local file path
426
+ */
427
+ private fun resolveSourceUri(sourceUri: String): File =
428
+ when {
429
+ // Local file path without URI scheme
430
+ !sourceUri.startsWith("https://") && !sourceUri.startsWith("file://") -> File(sourceUri)
431
+
432
+ // File URI
433
+ sourceUri.startsWith("file://") -> File(URI(sourceUri))
434
+
435
+ // HTTP URI - throw an error
436
+ else -> {
437
+ throw Exception("HTTP URI is not supported. Use expo-file-system to download the file.")
438
+ }
439
+ }
440
+
441
+ override fun onReadyForSpeech(params: Bundle?) {
442
+ // Avoid sending this event if there was an error
443
+ // An error may preempt this event in the case of a permission error or a language not supported error
444
+ if (recognitionState != RecognitionState.ERROR) {
445
+ sendEvent("start", null)
446
+ recognitionState = RecognitionState.ACTIVE
447
+ }
448
+ }
449
+
450
+ override fun onBeginningOfSpeech() {
451
+ sendEvent("speechstart", null)
452
+ }
453
+
454
+ override fun onRmsChanged(rmsdB: Float) {
455
+ /*
456
+ val isSilent = rmsdB <= 0
457
+
458
+ if (!isSilent) {
459
+ lastTimeSoundDetected = System.currentTimeMillis()
460
+ }
461
+
462
+ // Call "soundstart" event if not already called
463
+ if (!isSilent && soundState != SoundState.ACTIVE) {
464
+ sendEvent("soundstart", null)
465
+ soundState = SoundState.ACTIVE
466
+ log("Changed sound state to ACTIVE")
467
+ return
468
+ }
469
+
470
+ // If the sound is silent for more than 150ms, send "soundend" event
471
+ if (isSilent && soundState == SoundState.ACTIVE && (System.currentTimeMillis() - lastTimeSoundDetected) > 150) {
472
+ sendEvent("soundend", null)
473
+ soundState = SoundState.SILENT
474
+ log("Changed sound state to SILENT")
475
+ }
476
+ */
477
+ }
478
+
479
+ override fun onBufferReceived(buffer: ByteArray?) {
480
+ // More sound has been received.
481
+ }
482
+
483
+ override fun onEndOfSpeech() {
484
+ // recognitionState = RecognitionState.INACTIVE
485
+ sendEvent("speechend", null)
486
+ log("onEndOfSpeech()")
487
+ }
488
+
489
+ override fun onError(error: Int) {
490
+ val errorInfo = getErrorInfo(error)
491
+ // Web Speech API:
492
+ // https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition/nomatch_event
493
+ if (error == SpeechRecognizer.ERROR_NO_MATCH) {
494
+ sendEvent("nomatch", null)
495
+ }
496
+
497
+ sendEvent("error", mapOf("error" to errorInfo.error, "message" to errorInfo.message))
498
+ teardownAndEnd(RecognitionState.ERROR)
499
+ log("onError() - ${errorInfo.error}: ${errorInfo.message} - code: $error")
500
+ }
501
+
502
+ private fun getResults(results: Bundle?): List<Map<String, Any>> {
503
+ val resultsList = mutableListOf<Map<String, Any>>()
504
+ val confidences = results?.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES)
505
+
506
+ results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.let { matches ->
507
+ resultsList.addAll(
508
+ matches.mapIndexed { index, transcript ->
509
+ val confidence = confidences?.getOrNull(index) ?: 0f
510
+ mapOf(
511
+ "transcript" to transcript,
512
+ "confidence" to confidence,
513
+ "segments" to if (index == 0) getSegmentConfidences(results) else listOf(),
514
+ )
515
+ },
516
+ )
517
+ }
518
+
519
+ return resultsList
520
+ }
521
+
522
+ private fun getSegmentConfidences(results: Bundle?): List<Map<String, Any>> {
523
+ if (results == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
524
+ return listOf()
525
+ }
526
+
527
+ val recognitionParts =
528
+ results.getParcelableArrayList(SpeechRecognizer.RECOGNITION_PARTS, RecognitionPart::class.java)
529
+ ?: return listOf()
530
+
531
+ return recognitionParts
532
+ .mapIndexed { index, it ->
533
+ // Just set the endTime as the next word minus a millisecond
534
+ val nextPart = recognitionParts.getOrNull(index + 1)
535
+ val endTime =
536
+ if (nextPart != null) {
537
+ nextPart.timestampMillis - 1
538
+ } else {
539
+ it.timestampMillis
540
+ }
541
+ mapOf(
542
+ "startTimeMillis" to it.timestampMillis,
543
+ // get index of next part
544
+ "endTimeMillis" to endTime,
545
+ "segment" to if (it.formattedText.isNullOrEmpty()) it.rawText else it.formattedText!!,
546
+ "confidence" to confidenceLevelToFloat(it.confidenceLevel),
547
+ )
548
+ }
549
+ }
550
+
551
+ private fun confidenceLevelToFloat(confidenceLevel: Int): Float =
552
+ when (confidenceLevel) {
553
+ RecognitionPart.CONFIDENCE_LEVEL_HIGH -> 1.0f
554
+ RecognitionPart.CONFIDENCE_LEVEL_MEDIUM_HIGH -> 0.8f
555
+ RecognitionPart.CONFIDENCE_LEVEL_MEDIUM -> 0.6f
556
+ RecognitionPart.CONFIDENCE_LEVEL_MEDIUM_LOW -> 0.4f
557
+ RecognitionPart.CONFIDENCE_LEVEL_LOW -> 0.2f
558
+ RecognitionPart.CONFIDENCE_LEVEL_UNKNOWN -> -1.0f
559
+ else -> 0.0f
560
+ }
561
+
562
+ override fun onResults(results: Bundle?) {
563
+ val resultsList = getResults(results)
564
+
565
+ if (resultsList.isEmpty()) {
566
+ // https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition/nomatch_event
567
+ // The nomatch event of the Web Speech API is fired
568
+ // when the speech recognition service returns a final result with no significant recognition.
569
+ sendEvent("nomatch", null)
570
+ } else {
571
+ sendEvent(
572
+ "result",
573
+ mapOf(
574
+ "results" to resultsList,
575
+ "isFinal" to true,
576
+ ),
577
+ )
578
+ }
579
+ log("onResults(), results: $resultsList")
580
+
581
+ teardownAndEnd()
582
+ }
583
+
584
+ override fun onPartialResults(partialResults: Bundle?) {
585
+ val partialResultsList = getResults(partialResults)
586
+ // Avoid sending result event if there was an empty result, or the first result is an empty string
587
+ val nonEmptyStrings = partialResultsList.filter { it["transcript"]?.toString()?.isNotEmpty() ?: false }
588
+
589
+ log("onPartialResults(), results: $nonEmptyStrings")
590
+ if (nonEmptyStrings.isNotEmpty()) {
591
+ sendEvent("result", mapOf("results" to nonEmptyStrings, "isFinal" to false))
592
+ }
593
+ }
594
+
595
+ /**
596
+ * For API 33: Basically same as onResults but doesn't stop
597
+ */
598
+ override fun onSegmentResults(segmentResults: Bundle) {
599
+ val resultsList = getResults(segmentResults)
600
+ if (resultsList.isEmpty()) {
601
+ sendEvent("nomatch", null)
602
+ } else {
603
+ sendEvent(
604
+ "result",
605
+ mapOf(
606
+ "results" to resultsList,
607
+ "isFinal" to true,
608
+ ),
609
+ )
610
+ }
611
+ log("onSegmentResults(), transcriptions: $resultsList")
612
+
613
+ // If the user opted to stop
614
+ if (recognitionState == RecognitionState.STOPPING) {
615
+ teardownAndEnd()
616
+ }
617
+ }
618
+
619
+ override fun onEndOfSegmentedSession() {
620
+ log("onEndOfSegmentedSession()")
621
+ teardownAndEnd()
622
+ }
623
+
624
+ override fun onEvent(
625
+ eventType: Int,
626
+ params: Bundle?,
627
+ ) {
628
+ // Reserved for future events
629
+ }
630
+
631
+ private fun getErrorInfo(errorCode: Int): SpeechRecognitionErrorEvent {
632
+ // Mapped to error
633
+ // https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognitionErrorEvent/error
634
+ val error: String =
635
+ when (errorCode) {
636
+ // Audio recording error.
637
+ SpeechRecognizer.ERROR_AUDIO -> "audio-capture"
638
+ SpeechRecognizer.ERROR_CLIENT -> "client"
639
+ SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "service-not-allowed"
640
+ SpeechRecognizer.ERROR_NETWORK -> "network"
641
+ SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "network"
642
+ SpeechRecognizer.ERROR_NO_MATCH -> "no-speech"
643
+ SpeechRecognizer.ERROR_SERVER -> "network"
644
+ // Extra codes
645
+ SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "speech-timeout"
646
+ SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "busy"
647
+ SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE -> "language-not-supported"
648
+ else -> "unknown"
649
+ }
650
+
651
+ val message: String =
652
+ when (errorCode) {
653
+ SpeechRecognizer.ERROR_AUDIO -> "Audio recording error."
654
+ SpeechRecognizer.ERROR_CLIENT -> "Other client side errors."
655
+ SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "Insufficient permissions"
656
+ SpeechRecognizer.ERROR_NETWORK -> "Other network related errors."
657
+ SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "Network operation timed out."
658
+ SpeechRecognizer.ERROR_NO_MATCH -> "No speech was detected."
659
+ SpeechRecognizer.ERROR_SERVER -> "Server sent error status."
660
+ // Extra codes/messages
661
+ SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "RecognitionService busy."
662
+ SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "No speech input."
663
+ SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE -> "Requested language is supported, but not yet downloaded."
664
+ else -> "Unknown error"
665
+ }
666
+
667
+ return SpeechRecognitionErrorEvent(error, message)
668
+ }
669
+ }