expo-speech-recognition 0.2.19 → 0.2.21

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 (34) hide show
  1. package/README.md +113 -43
  2. package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionModule.kt +4 -0
  3. package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechService.kt +11 -2
  4. package/build/ExpoSpeechRecognitionModule.d.ts +2 -40
  5. package/build/ExpoSpeechRecognitionModule.d.ts.map +1 -1
  6. package/build/ExpoSpeechRecognitionModule.js +1 -0
  7. package/build/ExpoSpeechRecognitionModule.js.map +1 -1
  8. package/build/ExpoSpeechRecognitionModule.types.d.ts +65 -43
  9. package/build/ExpoSpeechRecognitionModule.types.d.ts.map +1 -1
  10. package/build/ExpoSpeechRecognitionModule.types.js.map +1 -1
  11. package/build/ExpoSpeechRecognitionModule.web.d.ts.map +1 -1
  12. package/build/ExpoSpeechRecognitionModule.web.js +5 -4
  13. package/build/ExpoSpeechRecognitionModule.web.js.map +1 -1
  14. package/build/ExpoWebSpeechRecognition.d.ts +1 -1
  15. package/build/ExpoWebSpeechRecognition.d.ts.map +1 -1
  16. package/build/ExpoWebSpeechRecognition.js +2 -2
  17. package/build/ExpoWebSpeechRecognition.js.map +1 -1
  18. package/build/index.d.ts +14 -1
  19. package/build/index.d.ts.map +1 -1
  20. package/build/index.js +4 -0
  21. package/build/index.js.map +1 -1
  22. package/build/useSpeechRecognitionEvent.d.ts +1 -1
  23. package/build/useSpeechRecognitionEvent.d.ts.map +1 -1
  24. package/build/useSpeechRecognitionEvent.js +1 -1
  25. package/build/useSpeechRecognitionEvent.js.map +1 -1
  26. package/ios/ExpoSpeechRecognitionModule.swift +39 -4
  27. package/ios/ExpoSpeechRecognizer.swift +0 -3
  28. package/package.json +1 -1
  29. package/src/ExpoSpeechRecognitionModule.ts +3 -1
  30. package/src/ExpoSpeechRecognitionModule.types.ts +76 -45
  31. package/src/ExpoSpeechRecognitionModule.web.ts +8 -12
  32. package/src/ExpoWebSpeechRecognition.ts +6 -9
  33. package/src/index.ts +16 -0
  34. package/src/useSpeechRecognitionEvent.ts +2 -2
package/README.md CHANGED
@@ -18,13 +18,14 @@ expo-speech-recognition implements the iOS [`SFSpeechRecognizer`](https://develo
18
18
  - [Persisting Audio Recordings](#persisting-audio-recordings)
19
19
  - [Transcribing audio files](#transcribing-audio-files)
20
20
  - [Supported input audio formats](#supported-input-audio-formats)
21
- - [Android](#android)
22
- - [iOS](#ios)
23
21
  - [File transcription example](#file-transcription-example)
24
22
  - [Polyfilling the Web SpeechRecognition API](#polyfilling-the-web-speechrecognition-api)
25
23
  - [Muting the beep sound on Android](#muting-the-beep-sound-on-android)
26
24
  - [Improving accuracy of single-word prompts](#improving-accuracy-of-single-word-prompts)
27
25
  - [Platform Compatibility Table](#platform-compatibility-table)
26
+ - [Common Troubleshooting issues](#common-troubleshooting-issues)
27
+ - [Android issues](#android-issues)
28
+ - [iOS issues](#ios-issues)
28
29
  - [API Methods](#api-methods)
29
30
  - [start()](#startoptions-speechrecognitionoptions-void)
30
31
  - [stop()](#stop-void)
@@ -32,13 +33,14 @@ expo-speech-recognition implements the iOS [`SFSpeechRecognizer`](https://develo
32
33
  - [requestPermissionsAsync()](#requestpermissionsasync-promisepermissionresponse)
33
34
  - [getPermissionsAsync()](#getpermissionsasync-promisepermissionresponse)
34
35
  - [getStateAsync()](#getstateasync-promisespeechrecognitionstate)
35
- - [addSpeechRecognitionListener()](#addspeechrecognitionlistenereventname-string-listener-event-any--void--remove---void-)
36
+ - [addSpeechRecognitionListener()](#addspeechrecognitionlistener)
36
37
  - [getSupportedLocales()](#getsupportedlocales-promise-locales-string-installedlocales-string-)
37
38
  - [getSpeechRecognitionServices()](#getspeechrecognitionservices-string-android-only)
38
39
  - [getDefaultRecognitionService()](#getdefaultrecognitionservice--packagename-string--android-only)
39
40
  - [getAssistantService()](#getassistantservice--packagename-string--android-only)
41
+ - [isRecognitionAvailable()](#isrecognitionavailable-boolean)
40
42
  - [supportsOnDeviceRecognition()](#supportsondevicerecognition-boolean)
41
- - [supportsRecording()](#supportsrecording-boolean-android-only)
43
+ - [supportsRecording()](#supportsrecording-boolean)
42
44
  - [androidTriggerOfflineModelDownload()](#androidtriggerofflinemodeldownload-locale-string--promise-status-opened_dialog--download_success--download_canceled-message-string-)
43
45
  - [setCategoryIOS()](#setcategoryios-void-ios-only)
44
46
  - [getAudioSessionCategoryAndOptionsIOS()](#getaudiosessioncategoryandoptionsios-ios-only)
@@ -228,7 +230,9 @@ ExpoSpeechRecognitionModule.start({
228
230
  interimResults: true,
229
231
  // The maximum number of alternative transcriptions to return.
230
232
  maxAlternatives: 1,
231
- // Continuous recognition. Note: if false on iOS, recognition will run until no speech is detected for 3 seconds
233
+ // [Default: false] Continuous recognition.
234
+ // If false on iOS, recognition will run until no speech is detected for 3 seconds.
235
+ // Not supported on Android 12 and below.
232
236
  continuous: true,
233
237
  // [Default: false] Prevent device from sending audio over the network. Only enabled if the device supports it.
234
238
  requiresOnDeviceRecognition: false,
@@ -252,7 +256,7 @@ ExpoSpeechRecognitionModule.start({
252
256
  mode: "measurement",
253
257
  },
254
258
  // [Default: undefined] Recording options for Android & iOS
255
- // For Android, this is only supported on Android 13 and above.
259
+ // Android 13+ and iOS only.
256
260
  recordingOptions: {
257
261
  // [Default: false] Whether to persist the audio to a local file path.
258
262
  persist: false,
@@ -304,7 +308,7 @@ Events are largely based on the [Web Speech API](https://developer.mozilla.org/e
304
308
  | ------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
305
309
  | `audiostart` | Audio capturing has started | Includes the `uri` if `recordingOptions.persist` is enabled. |
306
310
  | `audioend` | Audio capturing has ended | Includes the `uri` if `recordingOptions.persist` is enabled. |
307
- | `end` | Speech recognition service has disconnected. | This should be the last event dispatched. |
311
+ | `end` | Speech recognition service has disconnected. | This should always be the last event dispatched, including after errors. |
308
312
  | `error` | Fired when a speech recognition error occurs. | You'll also receive an `error` event (with code "aborted") when calling `.abort()` |
309
313
  | `nomatch` | Speech recognition service returns a final result with no significant recognition. | You may have non-final results recognized. This may get emitted after cancellation. |
310
314
  | `result` | Speech recognition service returns a word or phrase has been positively recognized. | On Android, continous mode runs as a segmented session, meaning when a final result is reached, additional partial and final results will cover a new segment separate from the previous final result. On iOS, you should expect one final result before speech recognition has stopped. |
@@ -336,27 +340,29 @@ useSpeechRecognitionEvent("error", (event) => {
336
340
  const error: ExpoSpeechRecognitionErrorCode = "audio-capture";
337
341
  ```
338
342
 
339
- The error code is largely based on the Web Speech API error codes.
340
-
341
- | Error Code | Description |
342
- | ------------------------ | -------------------------------------------------------------------------- |
343
- | `aborted` | The user called `ExpoSpeechRecognitionModule.abort()` |
344
- | `audio-capture` | Audio recording error. |
345
- | `bad-grammar` | Provided grammar is invalid. (Note: web only) |
346
- | `language-not-supported` | Locale is not supported by the speech recognizer. |
347
- | `network` | Network communication required for completing the recognition failed. |
348
- | `no-speech` | No final speech was detected. |
349
- | `not-allowed` | Permission to use speech recognition or microphone was not granted. |
350
- | `service-not-allowed` | Recognizer is unavailable. |
351
- | `busy` | The recognizer is busy and cannot accept any new recognition requests. |
352
- | `client` | (Android) Unknown error. Corresponds with `SpeechRecognizer.ERROR_CLIENT`. |
343
+ The error code is based on the [Web Speech API error codes](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognitionErrorEvent/error).
344
+
345
+ | Error Code | Description |
346
+ | ------------------------ | ------------------------------------------------------------------------------- |
347
+ | `aborted` | The user called `ExpoSpeechRecognitionModule.abort()` |
348
+ | `audio-capture` | Audio recording error. |
349
+ | `bad-grammar` | Provided grammar is invalid. (Web only) |
350
+ | `language-not-supported` | Locale is not supported by the speech recognizer. |
351
+ | `network` | Network communication required for completing the recognition failed. |
352
+ | `no-speech` | No final speech was detected. |
353
+ | `not-allowed` | Permission to use speech recognition or microphone was not granted. |
354
+ | `service-not-allowed` | Recognizer is unavailable. |
355
+ | `busy` | The recognizer is busy and cannot accept any new recognition requests. |
356
+ | `client` | An unknown client-side error. Corresponds with `SpeechRecognizer.ERROR_CLIENT`. |
357
+ | `speech-timeout` | (Android) No speech input. |
358
+ | `unknown` | (Android) Unknown error |
353
359
 
354
360
  ## Persisting Audio Recordings
355
361
 
356
362
  If you would like to persist the recognized audio for later use, you can enable the `recordingOptions.persist` option when calling `start()`. Enabling this setting will emit an `{ uri: string }` event object in the `audiostart` and `audioend` events with the local file path.
357
363
 
358
364
  > [!IMPORTANT]
359
- > For Android, this is only supported on Android 13 and above. Call `supportsRecording()` to see if it's available before using this feature.
365
+ > This feature is available on Android 13+ and iOS. Call [`supportsRecording()`](#supportsrecording-boolean) to see if it's available before using this feature.
360
366
 
361
367
  Default audio output formats:
362
368
 
@@ -439,11 +445,11 @@ function AudioPlayer(props: { source: string }) {
439
445
 
440
446
  ## Transcribing audio files
441
447
 
442
- You can use the `audioSource.uri` option to transcribe audio files instead of using the microphone.
443
-
444
448
  > [!IMPORTANT]
445
449
  > This feature is available on Android 13+ and iOS. If the device does not support the feature, you'll receive an `error` event with the code `audio-capture`.
446
450
 
451
+ Instead of using the microphone, you can configure the `audioSource.uri` option to transcribe audio files.
452
+
447
453
  ### Supported input audio formats
448
454
 
449
455
  #### Android
@@ -598,6 +604,9 @@ recognition.abort();
598
604
 
599
605
  ## Muting the beep sound on Android
600
606
 
607
+ > [!NOTE]
608
+ > This only applies to Android 13 and above.
609
+
601
610
  On Android, you may notice that there's a beep sound when you start and stop speech recognition. This is due to a hardcoded behavior in the underlying SpeechRecognizer API. However, a workaround you can use is by enabling continuous recognition:
602
611
 
603
612
  ```ts
@@ -607,11 +616,19 @@ ExpoSpeechRecognitionModule.start({
607
616
  lang: "en-US",
608
617
  continuous: true,
609
618
  });
619
+
620
+ // Or enable recording persistence
621
+ ExpoSpeechRecognitionModule.start({
622
+ lang: "en-US",
623
+ recordingOptions: {
624
+ persist: true,
625
+ },
626
+ });
610
627
  ```
611
628
 
612
- Under the hood, this sets the `EXTRA_AUDIO_SOURCE` in the recognizer intent to a custom microphone source instead of using the default microphone setting.
629
+ Under the hood, both of these set the `EXTRA_AUDIO_SOURCE` in the recognizer intent to a custom microphone source instead of using the default microphone setting.
613
630
 
614
- To maintain the same behavior as non-continuous mode, you should listen for a result event with `isFinal: true` and then immediately call `abort()` to stop the recognition.
631
+ If you intend to use the first option and still want to maintain the same behavior as non-continuous mode, you should listen for a result event with `isFinal: true` and then immediately call `abort()` to stop the recognition.
615
632
 
616
633
  ## Improving accuracy of single-word prompts
617
634
 
@@ -628,7 +645,7 @@ As of 7 Aug 2024, the following platforms are supported:
628
645
 
629
646
  | Platform | Supported | Default Recognition Engine | Notes |
630
647
  | ---------------------- | --------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
631
- | Android (React Native) | ✅ | Google | Recording feature is only supported on Android 13 and above. Recognition engine can be changed via `androidRecognitionServicePackage` |
648
+ | Android (React Native) | ✅ | Google | Continuous mode and Recording features are only supported on Android 13 and above. Recognition engine can be changed via `androidRecognitionServicePackage` |
632
649
  | iOS (React Native) | ✅ | Siri | |
633
650
  | Chrome Desktop | ✅ | Google (server-based) | Implemented via prefix `webkitSpeechRecognition`. |
634
651
  | Safari Desktop >= v16 | ✅ | Siri | Implemented via prefix `webkitSpeechRecognition`. Siri needs to be enabled |
@@ -639,6 +656,40 @@ As of 7 Aug 2024, the following platforms are supported:
639
656
  | Brave Desktop | ❌ | - | As of Aug 2024, Brave is working on an implementation however there's currently no ETA (source: [brave-browser/issues/3725](https://github.com/brave/brave-browser/issues/3725#issuecomment-2224068859)) |
640
657
  | Firefox Desktop | ❌ | - | No SpeechRecognition implementation |
641
658
 
659
+ ## Common Troubleshooting Issues
660
+
661
+ ### Android issues
662
+
663
+ #### Single words/letters/characters not recognized
664
+
665
+ See [Improving accuracy of single-word prompts](#improving-accuracy-of-single-word-prompts).
666
+
667
+ #### Speech recognition unavailable, not supported, or hanging
668
+
669
+ - For Android 13+, check if the device has the [Speech Recognition & Synthesis](https://play.google.com/store/apps/details?id=com.google.android.tts) (`com.google.android.tts`) package installed **and enabled**. If it was previously disabled, you may need to restart the device for the changes to take effect.
670
+ - For Android 12 and lower, check if the device has the [Google app](https://play.google.com/store/apps/details?id=com.google.android.googlequicksearchbox) (`com.google.android.googlequicksearchbox`) package installed **and enabled**.
671
+ - Use the `getSpeechRecognitionServices()` function to see what services are available on the device and `getDefaultRecognitionService()` to see which service is the default.
672
+
673
+ #### On-device recognition not working
674
+
675
+ On an Android 12 emulator, I couldn't verify whether on-device recognition works (and there's no online resources that seem to verify that it works). You'll likely see that it starts and then stops with a "error" event and the code `no-speech`.
676
+
677
+ For Android 13 and above however, you can try the following:
678
+
679
+ - Call the `getSupportedLocales()` function to see what installed locales are supported by the device. On Android 13+, you likely won't see any locales installed. If that is the case, you can call `androidTriggerOfflineModelDownload()` to download an offline model for a specific locale you want to use in order to use on-device recognition.
680
+ - If you still can't get it to work, you may want to double check if the locale is installed by opening the Android System Intelligence app (which is somewhat hidden through a few screens in the Settings app). You can navigate there through the following steps:
681
+ `Settings -> Security and privacy -> More privacy settings -> Android System Intelligence -> On-device speech recognition`, or watch [this video](https://github.com/jamsch/expo-speech-recognition/issues/8#issuecomment-2309557322).
682
+
683
+ ### iOS issues
684
+
685
+ #### Audio session issues / crashes
686
+
687
+ If you're running a multimedia application with audio or video playback, you'll need to keep in mind that this library does modify the current audio session category and mode which may cause issues. In order to work seamlessly in your application, you should make use of the following APIs:
688
+
689
+ - `getAudioSessionCategoryAndOptionsIOS()` to retrieve the current audio session category and options, you may want to use this prior to starting speech recognition
690
+ - `ExpoSpeechRecognitionModule.start({ iosCategory })` to configure the audio session category and mode when speech recognition starts
691
+ - `setAudioCategoryIOS({ category, categoryOptions, mode })` to set the audio session category and mode at a later point in time
692
+
642
693
  ## API Methods
643
694
 
644
695
  ### `start(options: SpeechRecognitionOptions): void`
@@ -689,9 +740,9 @@ For iOS, once a user has granted (or denied) location permissions by responding
689
740
  the only way that the permissions can be changed is by the user themselves using the device settings app.
690
741
 
691
742
  ```ts
692
- import { requestPermissionsAsync } from "expo-speech-recognition";
743
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
693
744
 
694
- requestPermissionsAsync().then((result) => {
745
+ ExpoSpeechRecognitionModule.requestPermissionsAsync().then((result) => {
695
746
  console.log("Status:", result.status); // "granted" | "denied" | "not-determined"
696
747
  console.log("Granted:", result.granted); // true | false
697
748
  console.log("Can ask again:", result.canAskAgain); // true | false
@@ -704,9 +755,9 @@ requestPermissionsAsync().then((result) => {
704
755
  Returns the current permission status for the microphone and speech recognition.
705
756
 
706
757
  ```ts
707
- import { getPermissionsAsync } from "expo-speech-recognition";
758
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
708
759
 
709
- getPermissionsAsync().then((result) => {
760
+ ExpoSpeechRecognitionModule.getPermissionsAsync().then((result) => {
710
761
  console.log("Status:", result.status); // "granted" | "denied" | "not-determined"
711
762
  console.log("Granted:", result.granted); // true | false
712
763
  console.log("Can ask again:", result.canAskAgain); // true | false
@@ -719,22 +770,25 @@ getPermissionsAsync().then((result) => {
719
770
  Returns the current internal state of the speech recognizer.
720
771
 
721
772
  ```ts
722
- import { getStateAsync } from "expo-speech-recognition";
773
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
723
774
 
724
775
  // Note: you probably should rather rely on the events emitted by the SpeechRecognition API instead
725
- getStateAsync().then((state) => {
776
+ ExpoSpeechRecognitionModule.getStateAsync().then((state) => {
726
777
  console.log("Current state:", state);
727
778
  // "inactive" | "starting" | "stopping" | "recognizing"
728
779
  });
729
780
  ```
730
781
 
731
- ### `addSpeechRecognitionListener(eventName: string, listener: (event: any) => void): { remove: () => void }`
782
+ ### `addSpeechRecognitionListener()`
783
+
784
+ Refer to [Speech Recognition Events](#speech-recognition-events) for the list of supported events.
732
785
 
733
786
  ```ts
734
787
  import { addSpeechRecognitionListener } from "expo-speech-recognition";
735
788
 
736
789
  const listener = addSpeechRecognitionListener("result", (event) => {
737
- console.log("result:", event.results[event.resultIndex][0].transcript);
790
+ console.log("transcript:", event.results[0]?.transcript);
791
+ console.log("confidence:", event.results[0]?.confidence);
738
792
  });
739
793
 
740
794
  // Remove the listener when you're done
@@ -787,7 +841,7 @@ Get list of speech recognition services available on the device.
787
841
  ```ts
788
842
  import { getSpeechRecognitionServices } from "expo-speech-recognition";
789
843
 
790
- const packages = ExpoSpeechRecognitionModule.getSpeechRecognitionServices();
844
+ const packages = getSpeechRecognitionServices();
791
845
  console.log("Speech recognition services:", packages.join(", "));
792
846
  // e.g. ["com.google.android.as", "com.google.android.tts", "com.samsung.android.bixby.agent"]
793
847
  ```
@@ -799,9 +853,10 @@ Returns the default voice recognition service on the device.
799
853
  ```ts
800
854
  import { getDefaultRecognitionService } from "expo-speech-recognition";
801
855
 
802
- const service = ExpoSpeechRecognitionModule.getDefaultRecognitionService();
856
+ const service = getDefaultRecognitionService();
803
857
  console.log("Default recognition service:", service.packageName);
804
- // Usually this is "com.google.android.tts", however "com.google.android.as" will likely be used for on-device recognition.
858
+ // Usually this is "com.google.android.tts" on Android 13+ and "com.google.android.googlequicksearchbox" on Android <=12.
859
+ // For on-device recognition, "com.google.android.as" will likely be used.
805
860
  ```
806
861
 
807
862
  ### `getAssistantService(): { packageName: string }` (Android only)
@@ -811,15 +866,30 @@ Returns the default voice assistant service on the device.
811
866
  ```ts
812
867
  import { getAssistantService } from "expo-speech-recognition";
813
868
 
814
- const service = ExpoSpeechRecognitionModule.getAssistantService();
869
+ const service = getAssistantService();
815
870
  console.log("Default assistant service:", service.packageName);
816
871
  // Usually "com.google.android.googlequicksearchbox" for Google
817
872
  // or "com.samsung.android.bixby.agent" for Samsung
818
873
  ```
819
874
 
875
+ ### `isRecognitionAvailable(): boolean`
876
+
877
+ Whether speech recognition is currently available on the device.
878
+
879
+ If this method returns false, calling `start()` will fail and emit an error event with the code `service-not-allowed` or `language-not-supported`. You should also ask the user to enable speech recognition in the system settings (i.e, for iOS to enable Siri & Dictation). On Android, you should ask the user to install and enable `com.google.android.tts` (Android 13+) or `com.google.android.googlequicksearchbox` (Android <= 12) as a default voice recognition service.
880
+
881
+ For Web, this method only checks if the browser has the Web SpeechRecognition API available, however keep in mind that browsers (like Brave) may still have the APIs but not have it implemented yet. Refer to [Platform Compatibility Table](#platform-compatibility-table) for more information. You may want to use a user agent parser to fill in the gaps.
882
+
883
+ ```ts
884
+ import { isRecognitionAvailable } from "expo-speech-recognition";
885
+
886
+ const available = isRecognitionAvailable();
887
+ console.log("Speech recognition available:", available);
888
+ ```
889
+
820
890
  ### `supportsOnDeviceRecognition(): boolean`
821
891
 
822
- Whether on-device speech recognition is available on the device.
892
+ Whether the device supports on-device speech recognition.
823
893
 
824
894
  ```ts
825
895
  import { supportsOnDeviceRecognition } from "expo-speech-recognition";
@@ -828,7 +898,7 @@ const available = supportsOnDeviceRecognition();
828
898
  console.log("OnDevice recognition available:", available);
829
899
  ```
830
900
 
831
- ### `supportsRecording(): boolean` (Android only)
901
+ ### `supportsRecording(): boolean`
832
902
 
833
903
  Whether audio recording is supported during speech recognition. This mostly applies to Android devices, to check if it's at least Android 13.
834
904
 
@@ -848,10 +918,10 @@ You can see which locales are supported and installed on your device by running
848
918
  To download the offline model for a specific locale, use the `androidTriggerOfflineModelDownload` function.
849
919
 
850
920
  ```ts
851
- import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
921
+ import { androidTriggerOfflineModelDownload } from "expo-speech-recognition";
852
922
 
853
923
  // Download the offline model for the specified locale
854
- ExpoSpeechRecognitionModule.androidTriggerOfflineModelDownload({
924
+ androidTriggerOfflineModelDownload({
855
925
  locale: "en-US",
856
926
  })
857
927
  .then((result) => {
@@ -183,6 +183,10 @@ class ExpoSpeechRecognitionModule : Module() {
183
183
  }
184
184
  }
185
185
 
186
+ Function("isRecognitionAvailable") {
187
+ SpeechRecognizer.isRecognitionAvailable(appContext.reactContext!!)
188
+ }
189
+
186
190
  Function("supportsRecording") {
187
191
  Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
188
192
  }
@@ -49,8 +49,10 @@ class ExpoSpeechService(
49
49
  ) : RecognitionListener {
50
50
  private var speech: SpeechRecognizer? = null
51
51
  private val mainHandler = Handler(Looper.getMainLooper())
52
+
52
53
  /** Audio recorder for persisting audio */
53
54
  private var audioRecorder: ExpoAudioRecorder? = null
55
+
54
56
  /** File streamer for file-based recognition */
55
57
  private var delayedFileStreamer: DelayedFileStreamer? = null
56
58
  private var soundState = SoundState.INACTIVE
@@ -641,10 +643,13 @@ class ExpoSpeechService(
641
643
  SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "network"
642
644
  SpeechRecognizer.ERROR_NO_MATCH -> "no-speech"
643
645
  SpeechRecognizer.ERROR_SERVER -> "network"
646
+ SpeechRecognizer.ERROR_SERVER_DISCONNECTED -> "network"
647
+ SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE -> "language-not-supported"
648
+ SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED -> "language-not-supported"
644
649
  // Extra codes
645
650
  SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "speech-timeout"
646
651
  SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "busy"
647
- SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE -> "language-not-supported"
652
+ SpeechRecognizer.ERROR_TOO_MANY_REQUESTS -> "busy"
648
653
  else -> "unknown"
649
654
  }
650
655
 
@@ -657,10 +662,14 @@ class ExpoSpeechService(
657
662
  SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "Network operation timed out."
658
663
  SpeechRecognizer.ERROR_NO_MATCH -> "No speech was detected."
659
664
  SpeechRecognizer.ERROR_SERVER -> "Server sent error status."
665
+ SpeechRecognizer.ERROR_SERVER_DISCONNECTED -> "Server disconnected."
666
+ SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE -> "Requested language is supported, but not yet downloaded."
667
+ SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED ->
668
+ "Requested language is not available to be used with the current recognizer."
660
669
  // Extra codes/messages
661
670
  SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "RecognitionService busy."
671
+ SpeechRecognizer.ERROR_TOO_MANY_REQUESTS -> "Too many requests."
662
672
  SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "No speech input."
663
- SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE -> "Requested language is supported, but not yet downloaded."
664
673
  else -> "Unknown error"
665
674
  }
666
675
 
@@ -1,43 +1,5 @@
1
1
  import { EventEmitter } from "expo-modules-core";
2
- export declare const ExpoSpeechRecognitionModule: {
3
- stop: () => void;
4
- abort: () => void;
5
- requestPermissionsAsync: () => Promise<import("expo-modules-core").PermissionResponse>;
6
- getPermissionsAsync: () => Promise<import("expo-modules-core").PermissionResponse>;
7
- getStateAsync: () => Promise<"inactive" | "starting" | "recognizing" | "stopping">;
8
- getAssistantService: () => {
9
- packageName: string;
10
- };
11
- getDefaultRecognitionService: () => {
12
- packageName: string;
13
- };
14
- getSpeechRecognitionServices: () => string[];
15
- supportsOnDeviceRecognition: () => boolean;
16
- supportsRecording: () => boolean;
17
- start(options: import("./ExpoSpeechRecognitionModule.types").ExpoSpeechRecognitionOptions): void;
18
- getSupportedLocales(options: {
19
- androidRecognitionServicePackage?: string;
20
- }): Promise<{
21
- locales: string[];
22
- installedLocales: string[];
23
- }>;
24
- androidTriggerOfflineModelDownload(options: {
25
- locale: string;
26
- }): Promise<{
27
- status: "download_success" | "opened_dialog" | "download_canceled";
28
- message: string;
29
- }>;
30
- setCategoryIOS(options: import("./ExpoSpeechRecognitionModule.types").SetCategoryOptions): void;
31
- getAudioSessionCategoryAndOptionsIOS(): {
32
- category: import("./ExpoSpeechRecognitionModule.types").AVAudioSessionCategoryValue;
33
- categoryOptions: import("./ExpoSpeechRecognitionModule.types").AVAudioSessionCategoryOptionsValue[];
34
- mode: import("./ExpoSpeechRecognitionModule.types").AVAudioSessionModeValue;
35
- };
36
- setAudioSessionActiveIOS(value: boolean, options?: {
37
- notifyOthersOnDeactivation: boolean;
38
- }): void;
39
- addListener: (eventType: string) => void;
40
- removeListeners: (count: number) => void;
41
- };
2
+ import type { ExpoSpeechRecognitionModuleType } from "./ExpoSpeechRecognitionModule.types";
3
+ export declare const ExpoSpeechRecognitionModule: ExpoSpeechRecognitionModuleType;
42
4
  export declare const ExpoSpeechRecognitionModuleEmitter: EventEmitter;
43
5
  //# sourceMappingURL=ExpoSpeechRecognitionModule.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ExpoSpeechRecognitionModule.d.ts","sourceRoot":"","sources":["../src/ExpoSpeechRecognitionModule.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EAGb,MAAM,mBAAmB,CAAC;AAS3B,eAAO,MAAM,2BAA2B;;;;;;;;;;;;;;;;;wCAyBqtrB,CAAC;;;;;;;;;;;;;;;;;;;;;;CAL7vrB,CAAC;AAEF,eAAO,MAAM,kCAAkC,cAE9C,CAAC"}
1
+ {"version":3,"file":"ExpoSpeechRecognitionModule.d.ts","sourceRoot":"","sources":["../src/ExpoSpeechRecognitionModule.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EAGb,MAAM,mBAAmB,CAAC;AAE3B,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,qCAAqC,CAAC;AAO3F,eAAO,MAAM,2BAA2B,EAAE,+BAsBzC,CAAC;AAEF,eAAO,MAAM,kCAAkC,cAE9C,CAAC"}
@@ -15,6 +15,7 @@ export const ExpoSpeechRecognitionModule = {
15
15
  getSpeechRecognitionServices: () => ExpoSpeechRecognitionNativeModule.getSpeechRecognitionServices(),
16
16
  supportsOnDeviceRecognition: () => ExpoSpeechRecognitionNativeModule.supportsOnDeviceRecognition(),
17
17
  supportsRecording: () => ExpoSpeechRecognitionNativeModule.supportsRecording(),
18
+ isRecognitionAvailable: () => ExpoSpeechRecognitionNativeModule.isRecognitionAvailable(),
18
19
  };
19
20
  export const ExpoSpeechRecognitionModuleEmitter = new EventEmitter(ExpoSpeechRecognitionNativeModule ?? NativeModulesProxy.ExpoSpeechRecognition);
20
21
  //# sourceMappingURL=ExpoSpeechRecognitionModule.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ExpoSpeechRecognitionModule.js","sourceRoot":"","sources":["../src/ExpoSpeechRecognitionModule.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,mBAAmB,CAAC;AAI3B,kEAAkE;AAClE,4EAA4E;AAC5E,MAAM,iCAAiC,GACrC,mBAAmB,CAAkC,uBAAuB,CAAC,CAAC;AAEhF,MAAM,CAAC,MAAM,2BAA2B,GAAG;IACzC,GAAG,iCAAiC;IACpC,6DAA6D;IAC7D,IAAI,EAAE,GAAG,EAAE,CAAC,iCAAiC,CAAC,IAAI,EAAE;IACpD,KAAK,EAAE,GAAG,EAAE,CAAC,iCAAiC,CAAC,KAAK,EAAE;IACtD,uBAAuB,EAAE,GAAG,EAAE,CAC5B,iCAAiC,CAAC,uBAAuB,EAAE;IAC7D,mBAAmB,EAAE,GAAG,EAAE,CACxB,iCAAiC,CAAC,mBAAmB,EAAE;IACzD,aAAa,EAAE,GAAG,EAAE,CAAC,iCAAiC,CAAC,aAAa,EAAE;IACtE,mBAAmB,EAAE,GAAG,EAAE,CACxB,iCAAiC,CAAC,mBAAmB,EAAE;IACzD,4BAA4B,EAAE,GAAG,EAAE,CACjC,iCAAiC,CAAC,4BAA4B,EAAE;IAClE,4BAA4B,EAAE,GAAG,EAAE,CACjC,iCAAiC,CAAC,4BAA4B,EAAE;IAClE,2BAA2B,EAAE,GAAG,EAAE,CAChC,iCAAiC,CAAC,2BAA2B,EAAE;IACjE,iBAAiB,EAAE,GAAG,EAAE,CACtB,iCAAiC,CAAC,iBAAiB,EAAE;CACxD,CAAC;AAEF,MAAM,CAAC,MAAM,kCAAkC,GAAG,IAAI,YAAY,CAChE,iCAAiC,IAAI,kBAAkB,CAAC,qBAAqB,CAC9E,CAAC","sourcesContent":["import {\n EventEmitter,\n NativeModulesProxy,\n requireNativeModule,\n} from \"expo-modules-core\";\n\nimport type { ExpoSpeechRecognitionModuleType } from \"./ExpoSpeechRecognitionModule.types\";\n\n// It loads the native module object from the JSI or falls back to\n// the bridge module (from NativeModulesProxy) if the remote debugger is on.\nconst ExpoSpeechRecognitionNativeModule =\n requireNativeModule<ExpoSpeechRecognitionModuleType>(\"ExpoSpeechRecognition\");\n\nexport const ExpoSpeechRecognitionModule = {\n ...ExpoSpeechRecognitionNativeModule,\n // Avoid any function bindings when calling the native module\n stop: () => ExpoSpeechRecognitionNativeModule.stop(),\n abort: () => ExpoSpeechRecognitionNativeModule.abort(),\n requestPermissionsAsync: () =>\n ExpoSpeechRecognitionNativeModule.requestPermissionsAsync(),\n getPermissionsAsync: () =>\n ExpoSpeechRecognitionNativeModule.getPermissionsAsync(),\n getStateAsync: () => ExpoSpeechRecognitionNativeModule.getStateAsync(),\n getAssistantService: () =>\n ExpoSpeechRecognitionNativeModule.getAssistantService(),\n getDefaultRecognitionService: () =>\n ExpoSpeechRecognitionNativeModule.getDefaultRecognitionService(),\n getSpeechRecognitionServices: () =>\n ExpoSpeechRecognitionNativeModule.getSpeechRecognitionServices(),\n supportsOnDeviceRecognition: () =>\n ExpoSpeechRecognitionNativeModule.supportsOnDeviceRecognition(),\n supportsRecording: () =>\n ExpoSpeechRecognitionNativeModule.supportsRecording(),\n};\n\nexport const ExpoSpeechRecognitionModuleEmitter = new EventEmitter(\n ExpoSpeechRecognitionNativeModule ?? NativeModulesProxy.ExpoSpeechRecognition,\n);\n"]}
1
+ {"version":3,"file":"ExpoSpeechRecognitionModule.js","sourceRoot":"","sources":["../src/ExpoSpeechRecognitionModule.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,mBAAmB,CAAC;AAI3B,kEAAkE;AAClE,4EAA4E;AAC5E,MAAM,iCAAiC,GACrC,mBAAmB,CAAkC,uBAAuB,CAAC,CAAC;AAEhF,MAAM,CAAC,MAAM,2BAA2B,GAAoC;IAC1E,GAAG,iCAAiC;IACpC,6DAA6D;IAC7D,IAAI,EAAE,GAAG,EAAE,CAAC,iCAAiC,CAAC,IAAI,EAAE;IACpD,KAAK,EAAE,GAAG,EAAE,CAAC,iCAAiC,CAAC,KAAK,EAAE;IACtD,uBAAuB,EAAE,GAAG,EAAE,CAC5B,iCAAiC,CAAC,uBAAuB,EAAE;IAC7D,mBAAmB,EAAE,GAAG,EAAE,CACxB,iCAAiC,CAAC,mBAAmB,EAAE;IACzD,aAAa,EAAE,GAAG,EAAE,CAAC,iCAAiC,CAAC,aAAa,EAAE;IACtE,mBAAmB,EAAE,GAAG,EAAE,CACxB,iCAAiC,CAAC,mBAAmB,EAAE;IACzD,4BAA4B,EAAE,GAAG,EAAE,CACjC,iCAAiC,CAAC,4BAA4B,EAAE;IAClE,4BAA4B,EAAE,GAAG,EAAE,CACjC,iCAAiC,CAAC,4BAA4B,EAAE;IAClE,2BAA2B,EAAE,GAAG,EAAE,CAChC,iCAAiC,CAAC,2BAA2B,EAAE;IACjE,iBAAiB,EAAE,GAAG,EAAE,CACtB,iCAAiC,CAAC,iBAAiB,EAAE;IACvD,sBAAsB,EAAE,GAAG,EAAE,CAC3B,iCAAiC,CAAC,sBAAsB,EAAE;CAC7D,CAAC;AAEF,MAAM,CAAC,MAAM,kCAAkC,GAAG,IAAI,YAAY,CAChE,iCAAiC,IAAI,kBAAkB,CAAC,qBAAqB,CAC9E,CAAC","sourcesContent":["import {\n EventEmitter,\n NativeModulesProxy,\n requireNativeModule,\n} from \"expo-modules-core\";\n\nimport type { ExpoSpeechRecognitionModuleType } from \"./ExpoSpeechRecognitionModule.types\";\n\n// It loads the native module object from the JSI or falls back to\n// the bridge module (from NativeModulesProxy) if the remote debugger is on.\nconst ExpoSpeechRecognitionNativeModule =\n requireNativeModule<ExpoSpeechRecognitionModuleType>(\"ExpoSpeechRecognition\");\n\nexport const ExpoSpeechRecognitionModule: ExpoSpeechRecognitionModuleType = {\n ...ExpoSpeechRecognitionNativeModule,\n // Avoid any function bindings when calling the native module\n stop: () => ExpoSpeechRecognitionNativeModule.stop(),\n abort: () => ExpoSpeechRecognitionNativeModule.abort(),\n requestPermissionsAsync: () =>\n ExpoSpeechRecognitionNativeModule.requestPermissionsAsync(),\n getPermissionsAsync: () =>\n ExpoSpeechRecognitionNativeModule.getPermissionsAsync(),\n getStateAsync: () => ExpoSpeechRecognitionNativeModule.getStateAsync(),\n getAssistantService: () =>\n ExpoSpeechRecognitionNativeModule.getAssistantService(),\n getDefaultRecognitionService: () =>\n ExpoSpeechRecognitionNativeModule.getDefaultRecognitionService(),\n getSpeechRecognitionServices: () =>\n ExpoSpeechRecognitionNativeModule.getSpeechRecognitionServices(),\n supportsOnDeviceRecognition: () =>\n ExpoSpeechRecognitionNativeModule.supportsOnDeviceRecognition(),\n supportsRecording: () =>\n ExpoSpeechRecognitionNativeModule.supportsRecording(),\n isRecognitionAvailable: () =>\n ExpoSpeechRecognitionNativeModule.isRecognitionAvailable(),\n};\n\nexport const ExpoSpeechRecognitionModuleEmitter = new EventEmitter(\n ExpoSpeechRecognitionNativeModule ?? NativeModulesProxy.ExpoSpeechRecognition,\n);\n"]}
@@ -2,6 +2,45 @@ import type { PermissionResponse } from "expo-modules-core";
2
2
  import type { NativeModule } from "react-native";
3
3
  import type { AudioEncodingAndroid, AVAudioSessionCategory, AVAudioSessionCategoryOptions, AVAudioSessionMode, RecognizerIntentEnableLanguageSwitch, RecognizerIntentExtraLanguageModel, TaskHintIOS } from "./constants";
4
4
  export type AVAudioSessionCategoryValue = (typeof AVAudioSessionCategory)[keyof typeof AVAudioSessionCategory];
5
+ export type ExpoSpeechRecognitionResult = {
6
+ transcript: string;
7
+ /**
8
+ * Value ranging between between 0.0, 1.0, and -1 (unavailable) indicating transcript confidence.
9
+ */
10
+ confidence: number;
11
+ /**
12
+ * An array of transcription segments that represent the parts of the transcription, as identified by the speech recognizer.
13
+ *
14
+ * Notes for Android:
15
+ *
16
+ * - This is only available for SDK 34+ (Android 14+)
17
+ * - This is only verified to work with the `com.google.android.as` service (using on device speech recognition)
18
+ * - Segments are only available during the final result
19
+ * - The segment parts are split up by words.
20
+ * - The segments are only available for the first transcript
21
+ * - Segment confidences currently return as -1 (unavailable)
22
+ *
23
+ * Notes for iOS:
24
+ *
25
+ * - The confidence value will be 0 on partial results
26
+ */
27
+ segments: ExpoSpeechRecognitionResultSegment[];
28
+ };
29
+ export type ExpoSpeechRecognitionResultSegment = {
30
+ /** The start timestamp of the utterance, e.g. 1000 */
31
+ startTimeMillis: number;
32
+ /** The end timestamp of the utterance, e.g. 1500 */
33
+ endTimeMillis: number;
34
+ /** The text portion of the transcript, e.g. "Hello world" */
35
+ segment: string;
36
+ /** Value ranging between between 0.0, 1.0, and -1 (unavailable) indicating the confidence of the specific segment */
37
+ confidence: number;
38
+ };
39
+ /** Fired when there's a speech result. The result may be partial or final */
40
+ export type ExpoSpeechRecognitionResultEvent = {
41
+ isFinal: boolean;
42
+ results: ExpoSpeechRecognitionResult[];
43
+ };
5
44
  export type ExpoSpeechRecognitionErrorCode =
6
45
  /** The user called `ExpoSpeechRecognitionModule.abort()`. */
7
46
  "aborted"
@@ -22,52 +61,21 @@ export type ExpoSpeechRecognitionErrorCode =
22
61
  /** The recognizer is busy and cannot accept any new recognition requests. */
23
62
  | "busy"
24
63
  /** (Android only) An unknown client-side error occurred. */
25
- | "client";
64
+ | "client"
65
+ /** (Android) No speech input. */
66
+ | "speech-timeout"
67
+ /** (Android) Unknown error */
68
+ | "unknown";
69
+ export type ExpoSpeechRecognitionErrorEvent = {
70
+ error: ExpoSpeechRecognitionErrorCode;
71
+ message: string;
72
+ };
26
73
  /**
27
74
  * Events that are dispatched from the native side
28
75
  */
29
76
  export type ExpoSpeechRecognitionNativeEventMap = {
30
- /** Fired when there's a speech result. The result may be partial or final */
31
- result: {
32
- isFinal: boolean;
33
- results: {
34
- transcript: string;
35
- /**
36
- * Value ranging between between 0.0, 1.0, and -1 (unavailable) indicating transcript confidence.
37
- */
38
- confidence: number;
39
- /**
40
- * An array of transcription segments that represent the parts of the transcription, as identified by the speech recognizer.
41
- *
42
- * Notes for Android:
43
- *
44
- * - This is only available for SDK 34+ (Android 14+)
45
- * - This is only verified to work with the `com.google.android.as` service (using on device speech recognition)
46
- * - Segments are only available during the final result
47
- * - The segment parts are split up by words.
48
- * - The segments are only available for the first transcript
49
- * - Segment confidences currently return as -1 (unavailable)
50
- *
51
- * Notes for iOS:
52
- *
53
- * - The confidence value will be 0 on partial results
54
- */
55
- segments: {
56
- /** The start timestamp of the utterance, e.g. 1000 */
57
- startTimeMillis: number;
58
- /** The end timestamp of the utterance, e.g. 1500 */
59
- endTimeMillis: number;
60
- /** The text portion of the transcript, e.g. "Hello world" */
61
- segment: string;
62
- /** Value ranging between between 0.0, 1.0, and -1 (unavailable) indicating the confidence of the specific segment */
63
- confidence: number;
64
- }[];
65
- }[];
66
- };
67
- error: {
68
- error: ExpoSpeechRecognitionErrorCode;
69
- message: string;
70
- };
77
+ result: ExpoSpeechRecognitionResultEvent;
78
+ error: ExpoSpeechRecognitionErrorEvent;
71
79
  start: null;
72
80
  speechstart: null;
73
81
  speechend: null;
@@ -117,7 +125,13 @@ export type ExpoSpeechRecognitionOptions = {
117
125
  * On iOS, this configures [`SFSpeechRecognitionRequest.contextualStrings`](https://developer.apple.com/documentation/speech/sfspeechrecognitionrequest/1649391-contextualstrings).
118
126
  */
119
127
  contextualStrings?: string[];
120
- /** [Default: false] Continuous recognition. Note: if false on iOS, recognition will run until no speech is detected for 3 seconds */
128
+ /**
129
+ * [Default: false] Continuous recognition.
130
+ *
131
+ * Not supported on Android 12 and below.
132
+ *
133
+ * If false on iOS, recognition will run until no speech is detected for 3 seconds.
134
+ */
121
135
  continuous?: boolean;
122
136
  /** [Default: false] Prevent device from sending audio over the network. Only enabled if the device supports it.
123
137
  *
@@ -493,6 +507,7 @@ export interface ExpoSpeechRecognitionModuleType extends NativeModule {
493
507
  * @returns empty string if no service is found, or not Android
494
508
  */
495
509
  getDefaultRecognitionService(): {
510
+ /** e.g. "com.google.android.tts" or "com.google.android.googlequicksearchbox" */
496
511
  packageName: string;
497
512
  };
498
513
  /**
@@ -503,6 +518,7 @@ export interface ExpoSpeechRecognitionModuleType extends NativeModule {
503
518
  * @returns empty string if no service is found, or not Android
504
519
  */
505
520
  getAssistantService(): {
521
+ /** e.g. "com.google.android.googlequicksearchbox" or "com.samsung.android.bixby.agent" */
506
522
  packageName: string;
507
523
  };
508
524
  /**
@@ -515,6 +531,12 @@ export interface ExpoSpeechRecognitionModuleType extends NativeModule {
515
531
  * This mostly applies to Android devices, to check if it's greater than Android 13.
516
532
  */
517
533
  supportsRecording(): boolean;
534
+ /**
535
+ * Whether on-device speech recognition is available.
536
+ *
537
+ * If this method returns false, `start()` will fail and emit an error event with the code `service-not-allowed` or `language-not-supported`.
538
+ */
539
+ isRecognitionAvailable(): boolean;
518
540
  /**
519
541
  * Downloads the offline model for the specified locale.
520
542
  * Note: this is only supported on Android 13 and above.