expo-speech-recognition 0.2.24 → 1.0.0

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/CHANGELOG.md +17 -0
  2. package/README.md +93 -65
  3. package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionModule.kt +2 -0
  4. package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechService.kt +37 -3
  5. package/build/ExpoSpeechRecognitionModule.d.ts +0 -2
  6. package/build/ExpoSpeechRecognitionModule.d.ts.map +1 -1
  7. package/build/ExpoSpeechRecognitionModule.js +6 -18
  8. package/build/ExpoSpeechRecognitionModule.js.map +1 -1
  9. package/build/ExpoSpeechRecognitionModule.types.d.ts +34 -3
  10. package/build/ExpoSpeechRecognitionModule.types.d.ts.map +1 -1
  11. package/build/ExpoSpeechRecognitionModule.types.js.map +1 -1
  12. package/build/ExpoSpeechRecognitionModule.web.d.ts +43 -10
  13. package/build/ExpoSpeechRecognitionModule.web.d.ts.map +1 -1
  14. package/build/ExpoSpeechRecognitionModule.web.js +109 -105
  15. package/build/ExpoSpeechRecognitionModule.web.js.map +1 -1
  16. package/build/ExpoWebSpeechRecognition.d.ts.map +1 -1
  17. package/build/ExpoWebSpeechRecognition.js +4 -4
  18. package/build/ExpoWebSpeechRecognition.js.map +1 -1
  19. package/build/index.d.ts +3 -4
  20. package/build/index.d.ts.map +1 -1
  21. package/build/index.js +3 -3
  22. package/build/index.js.map +1 -1
  23. package/build/useSpeechRecognitionEvent.d.ts +2 -2
  24. package/build/useSpeechRecognitionEvent.d.ts.map +1 -1
  25. package/build/useSpeechRecognitionEvent.js +5 -9
  26. package/build/useSpeechRecognitionEvent.js.map +1 -1
  27. package/ios/ExpoSpeechRecognitionModule.swift +2 -0
  28. package/package.json +9 -4
  29. package/src/ExpoSpeechRecognitionModule.ts +6 -32
  30. package/src/ExpoSpeechRecognitionModule.types.ts +38 -3
  31. package/src/ExpoSpeechRecognitionModule.web.ts +172 -145
  32. package/src/ExpoWebSpeechRecognition.ts +5 -8
  33. package/src/index.ts +22 -33
  34. package/src/useSpeechRecognitionEvent.ts +11 -19
@@ -1 +1 @@
1
- {"version":3,"file":"ExpoSpeechRecognitionModule.types.js","sourceRoot":"","sources":["../src/ExpoSpeechRecognitionModule.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { PermissionResponse } from \"expo-modules-core\";\nimport type { NativeModule } from \"react-native\";\n\nimport type {\n AudioEncodingAndroid,\n AVAudioSessionCategory,\n AVAudioSessionCategoryOptions,\n AVAudioSessionMode,\n RecognizerIntentEnableLanguageSwitch,\n RecognizerIntentExtraLanguageModel,\n TaskHintIOS,\n} from \"./constants\";\n\nexport type AVAudioSessionCategoryValue =\n (typeof AVAudioSessionCategory)[keyof typeof AVAudioSessionCategory];\n\nexport type ExpoSpeechRecognitionResult = {\n transcript: string;\n /**\n * Value ranging between between 0.0, 1.0, and -1 (unavailable) indicating transcript confidence.\n */\n confidence: number;\n /**\n * An array of transcription segments that represent the parts of the transcription, as identified by the speech recognizer.\n *\n * Notes for Android:\n *\n * - This is only available for SDK 34+ (Android 14+)\n * - This is only verified to work with the `com.google.android.as` service (using on device speech recognition)\n * - Segments are only available during the final result\n * - The segment parts are split up by words.\n * - The segments are only available for the first transcript\n * - Segment confidences currently return as -1 (unavailable)\n *\n * Notes for iOS:\n *\n * - The confidence value will be 0 on partial results\n */\n segments: ExpoSpeechRecognitionResultSegment[];\n};\n\nexport type ExpoSpeechRecognitionResultSegment = {\n /** The start timestamp of the utterance, e.g. 1000 */\n startTimeMillis: number;\n /** The end timestamp of the utterance, e.g. 1500 */\n endTimeMillis: number;\n /** The text portion of the transcript, e.g. \"Hello world\" */\n segment: string;\n /** Value ranging between between 0.0, 1.0, and -1 (unavailable) indicating the confidence of the specific segment */\n confidence: number;\n};\n\n/** Fired when there's a speech result. The result may be partial or final */\nexport type ExpoSpeechRecognitionResultEvent = {\n isFinal: boolean;\n results: ExpoSpeechRecognitionResult[];\n};\n\nexport type ExpoSpeechRecognitionErrorCode =\n /** The user called `ExpoSpeechRecognitionModule.abort()`. */\n | \"aborted\"\n /** Audio recording error. */\n | \"audio-capture\"\n /** There was an error in the speech recognition grammar or semantic tags, or the chosen grammar format or semantic tag format was unsupported. */\n | \"bad-grammar\"\n /** Locale is not supported by the speech recognizer. */\n | \"language-not-supported\"\n /** Network communication required for completing the recognition failed. */\n | \"network\"\n /** No final speech was detected. */\n | \"no-speech\"\n /** Permission to use speech recognition or microphone was not granted. */\n | \"not-allowed\"\n /** Recognizer is unavailable. */\n | \"service-not-allowed\"\n // Extra codes (not part of the spec)\n /** The recognizer is busy and cannot accept any new recognition requests. */\n | \"busy\"\n /** (Android only) An unknown client-side error occurred. */\n | \"client\"\n /** (Android) No speech input. */\n | \"speech-timeout\"\n /** (Android) Unknown error */\n | \"unknown\";\n\nexport type ExpoSpeechRecognitionErrorEvent = {\n error: ExpoSpeechRecognitionErrorCode;\n message: string;\n};\n\n/**\n * Events that are dispatched from the native side\n */\nexport type ExpoSpeechRecognitionNativeEventMap = {\n result: ExpoSpeechRecognitionResultEvent;\n error: ExpoSpeechRecognitionErrorEvent;\n start: null;\n speechstart: null;\n speechend: null;\n /** A final result is returned with no significant recognition */\n nomatch: null;\n /** Audio capturing had started */\n audiostart: {\n /**\n * The uri is set when `recordingOptions.persist` is enabled.\n * Do not attempt to use this file until the `audioend` event is emitted.\n *\n * Example URIs:\n *\n * - Android: `file:///data/user/0/expo.modules.speechrecognition.example/cache/recording_1720678500903.wav`\n * - iOS: `file:///path/to/Library/Caches/audio_CD5E6C6C-3D9D-4754-9188-D6FAF97D9DF2.caf`\n */\n uri: string | null;\n };\n /** Audio capturing had ended */\n audioend: {\n /**\n * The uri is set when `recordingOptions.persist` is enabled.\n *\n * Example URIs:\n *\n * - Android: `file:///data/user/0/expo.modules.speechrecognition.example/cache/recording_1720678500903.wav`\n * - iOS: `file:///path/to/Library/Caches/audio_CD5E6C6C-3D9D-4754-9188-D6FAF97D9DF2.caf`\n */\n uri: string | null;\n };\n end: null;\n soundstart: null;\n soundend: null;\n volumechange: {\n /**\n * A float value between -2 and 10 indicating the volume of the input audio\n *\n * Consider anything below 0 to be inaudible\n */\n value: number;\n };\n};\n\nexport type ExpoSpeechRecognitionOptions = {\n /** [Default: \"en-US\"] The language of the speech recognition */\n lang?: string;\n /** [Default: false] Note for iOS: final results are only available after speech recognition has stopped */\n interimResults?: boolean;\n /** [Default: 5] The maximum number of alternative transcriptions to return. */\n maxAlternatives?: number;\n /**\n * An array of strings that will be used to provide context to the speech recognition engine.\n *\n * On Android, this configures [`EXTRA_BIASING_STRINGS`](https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_BIASING_STRINGS) in the recognizer intent (API level 33+).\n *\n * On iOS, this configures [`SFSpeechRecognitionRequest.contextualStrings`](https://developer.apple.com/documentation/speech/sfspeechrecognitionrequest/1649391-contextualstrings).\n */\n contextualStrings?: string[];\n /**\n * [Default: false] Continuous recognition.\n *\n * Not supported on Android 12 and below.\n *\n * If false, the behaviors are the following:\n *\n * - on iOS 17-, recognition will run until no speech is detected for 3 seconds.\n * - on iOS 18+ and Android, recognition will run until a result with `isFinal: true` is received.\n */\n continuous?: boolean;\n /** [Default: false] Prevent device from sending audio over the network. Only enabled if the device supports it.\n *\n * Use `getSupportedLocales()` to verify if the locale is installed on the device prior to enabling this option.\n */\n requiresOnDeviceRecognition?: boolean;\n /**\n * [Default: false] Include punctuation in the recognition results. This applies to full stops and commas.\n *\n * On Android, this configures [`EXTRA_ENABLE_FORMATTING`](https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_FORMATTING) in the recognizer intent (API level 33+).\n *\n * On iOS, this configures [`SFSpeechRecognitionRequest.addsPunctuation`](https://developer.apple.com/documentation/speech/sfspeechrecognitionrequest/3930023-addspunctuation).\n */\n addsPunctuation?: boolean;\n /**\n * The package name of the speech recognition service to use.\n * If not provided, the default service will be used.\n *\n * Obtain the supported packages by running `ExpoSpeechRecognitionModule.getSpeechRecognitionServices()`\n *\n * e.g. \"com.google.android.as\" or \"com.samsung.android.bixby.agent\"\n */\n androidRecognitionServicePackage?: string;\n /**\n * Extra options to provide to the Android Recognition intent.\n *\n * For a full list of options, see https://developer.android.com/reference/android/speech/RecognizerIntent\n */\n androidIntentOptions?: Partial<AndroidIntentOptions>;\n /**\n * Audio source options to pass to the recognizer.\n *\n * This option can be used to recognize audio from a local or remote file URI.\n */\n audioSource?: AudioSourceOptions;\n /**\n * Audio recording options for persisting the audio to a local file path.\n */\n recordingOptions?: RecordingOptions;\n /**\n * Default: `\"android.speech.action.RECOGNIZE_SPEECH\"`\n *\n * The kind of intent action\n *\n * Intents:\n *\n * - [`android.speech.action.RECOGNIZE_SPEECH`](https://developer.android.com/reference/android/speech/RecognizerIntent#ACTION_RECOGNIZE_SPEECH) which performs speech recognition (default)\n * - [`android.speech.action.VOICE_SEARCH_HANDS_FREE`](https://developer.android.com/reference/android/speech/RecognizerIntent#ACTION_VOICE_SEARCH_HANDS_FREE) - prompts the user for speech without requiring the user's visual attention or touch input\n * - [`android.speech.action.WEB_SEARCH`](https://developer.android.com/reference/android/speech/RecognizerIntent#ACTION_WEB_SEARCH) - displays a web search result or trigger another type of action based on the user's speech.\n */\n androidIntent?:\n | \"android.speech.action.RECOGNIZE_SPEECH\"\n | \"android.speech.action.VOICE_SEARCH_HANDS_FREE\"\n | \"android.speech.action.WEB_SEARCH\";\n\n /**\n * The hint for the speech recognition task.\n *\n * Default: `\"unspecified\"`\n *\n * Docs: https://developer.apple.com/documentation/speech/sfspeechrecognitiontaskhint\n */\n iosTaskHint?: IOSTaskHintValue;\n\n /**\n * The audio category for the speech recognition task.\n *\n * Use this option to configure the default audio session category and mode prior to starting speech recognition.\n *\n * **Caution:** confirm that the category, options and mode are compatible with the audio source.\n *\n * By default, the audio session category and mode are set to:\n *\n * - category: `playAndRecord`\n * - options: `defaultToSpeaker` and `allowBluetooth`\n * - mode: `measurement`\n *\n * Docs: https://developer.apple.com/documentation/avfaudio/avaudiosession/category\n */\n iosCategory?: SetCategoryOptions;\n\n /**\n * Settings for volume change events.\n */\n volumeChangeEventOptions?: {\n /**\n * Whether to emit volume change events.\n *\n * Default: false\n */\n enabled?: boolean;\n /**\n * Specifies the interval (in milliseconds) to emit `volumechange` events.\n *\n * Default: 100ms on iOS\n *\n * Increasing this value will improve performance\n */\n intervalMillis?: number;\n };\n};\n\nexport type IOSTaskHintValue = (typeof TaskHintIOS)[keyof typeof TaskHintIOS];\n\nexport type RecordingOptions = {\n /**\n * Whether to persist the audio to a local file path.\n *\n * Default: false\n */\n persist: boolean;\n /**\n * Default: `FileSystem.CacheDirectory`. This changes the default storage location for the audio file.\n */\n outputDirectory?: string;\n /**\n * Default: `\"recording_${timestamp|uuid}.[wav|caf]\"`. This changes the file name for the audio file.\n */\n outputFileName?: string;\n /**\n * Default: undefined. The sample rate of the output audio file.\n *\n * Only supported on iOS\n *\n * Default sample rate is: 16000 on Android, 44100/48000 on iOS\n */\n outputSampleRate?: number;\n /**\n * Default: undefined. The encoding of the output audio file.\n *\n * Only supported on iOS\n */\n outputEncoding?:\n | \"pcmFormatFloat32\"\n | \"pcmFormatFloat64\"\n | \"pcmFormatInt16\"\n | \"pcmFormatInt32\";\n};\n\nexport type AudioSourceOptions = {\n /**\n * Local audio source URI.\n *\n * e.g. `\"file:///storage/emulated/0/Download/audio.wav\"`\n */\n uri: string;\n /**\n * [Android only] The number of channels in the source audio.\n *\n * Default: 1\n */\n audioChannels?: number;\n /**\n * [Android only] A value from [AudioFormat](https://developer.android.com/reference/android/media/AudioFormat).\n *\n * Use the `AudioEncodingAndroid` enum to get the correct value.\n */\n audioEncoding?: AudioEncodingAndroidValue;\n /**\n * [Android only] Audio sampling rate in Hz.\n *\n * Default: 16000\n */\n sampleRate?: number;\n /**\n * [Android only] The delay for a 4KiB chunk of audio to stream to the speech recognition service.\n *\n * Use this setting to avoid being rate-limited when using network-based recognition.\n *\n * If you're using on-device recognition, you may want to increase this value to avoid unprocessed audio chunks.\n *\n * Default: 50ms for network-based recognition, 15ms for on-device recognition\n */\n chunkDelayMillis?: number;\n};\n\nexport type AudioEncodingAndroidValue =\n (typeof AudioEncodingAndroid)[keyof typeof AudioEncodingAndroid];\n\nexport type AndroidIntentOptions = {\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_CALLING_PACKAGE\n *\n * The extra key used in an intent to the speech recognizer for voice search. Not generally to be used by developers. The system search dialog uses this, for example, to set a calling package for identification by a voice search API. If this extra is set by anyone but the system process, it should be overridden by the voice search implementation.\n */\n EXTRA_CALLING_PACKAGE: string;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_BIASING_DEVICE_CONTEXT\n *\n * Optional boolean to enable biasing towards device context. The recognizer will use the device context to tune the recognition results.\n *\n * Depending on the recognizer implementation, this value may have no effect.\n */\n EXTRA_ENABLE_BIASING_DEVICE_CONTEXT: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_LANGUAGE_DETECTION\n *\n * Optional boolean indicating whether to enable language detection. When enabled, the recognizer will consistently identify the language of the current spoken utterance and provide that info via RecognitionListener#onLanguageDetection(Bundle).\n */\n EXTRA_ENABLE_LANGUAGE_DETECTION: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_LANGUAGE_SWITCH\n *\n * Optional string to enable automatic switching to the language being spoken with the desired sensitivity level, instead of being restricted to a single language. The corresponding language models must be downloaded to support the switch. Otherwise, the recognizer will report an error on a switch failure. The recognizer provides the switch results via RecognitionListener#onLanguageDetection(Bundle).\n *\n * Since detection is a necessary requirement for the language switching, setting this value implicitly enables EXTRA_ENABLE_LANGUAGE_DETECTION.\n *\n * Depending on the recognizer implementation, this value may have no effect.\n */\n EXTRA_ENABLE_LANGUAGE_SWITCH: (typeof RecognizerIntentEnableLanguageSwitch)[keyof typeof RecognizerIntentEnableLanguageSwitch];\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_HIDE_PARTIAL_TRAILING_PUNCTUATION\n *\n * [API level 33] Optional boolean, to be used with EXTRA_ENABLE_FORMATTING, to prevent the recognizer adding punctuation after the last word of the partial results. The default is false.\n */\n EXTRA_HIDE_PARTIAL_TRAILING_PUNCTUATION: boolean;\n /**\n * Optional list of IETF language tags (as defined by BCP 47, e.g. \"en-US\", \"de-DE\").\n *\n * [API level 34] This extra is to be used with EXTRA_ENABLE_LANGUAGE_DETECTION. If set, the recognizer will constrain the language detection output to this list of languages, potentially improving detection accuracy.\n */\n EXTRA_LANGUAGE_DETECTION_ALLOWED_LANGUAGES: string[];\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_LANGUAGE_MODEL\n *\n * [Default: free_form] The language model to use for speech recognition.\n *\n * Informs the recognizer which speech model to prefer when performing ACTION_RECOGNIZE_SPEECH.\n * The recognizer uses this information to fine tune the results.\n * This extra is required. Activities implementing ACTION_RECOGNIZE_SPEECH may interpret the values as they see fit.\n */\n EXTRA_LANGUAGE_MODEL: (typeof RecognizerIntentExtraLanguageModel)[keyof typeof RecognizerIntentExtraLanguageModel];\n\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_LANGUAGE_SWITCH_ALLOWED_LANGUAGES\n *\n * [API level 34] Optional list of IETF language tags (as defined by BCP 47, e.g. \"en-US\", \"de-DE\").\n * This extra is to be used with EXTRA_ENABLE_LANGUAGE_SWITCH. If set, the recognizer will apply the auto switch only to these languages, even if the speech models of other languages also exist.\n * The corresponding language models must be downloaded to support the switch. Otherwise, the recognizer will report an error on a switch failure.\n */\n EXTRA_LANGUAGE_SWITCH_ALLOWED_LANGUAGES: string[];\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_LANGUAGE_SWITCH_INITIAL_ACTIVE_DURATION_TIME_MILLIS\n *\n * [API level 35] Optional integer to use for EXTRA_ENABLE_LANGUAGE_SWITCH. If set, the language switch will only be activated for this value of ms of audio since the START_OF_SPEECH. This could provide a more stable recognition result when the language switch is only required in the beginning of the session.\n */\n EXTRA_LANGUAGE_SWITCH_INITIAL_ACTIVE_DURATION_TIME_MILLIS: number;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_LANGUAGE_SWITCH_MAX_SWITCHES\n *\n * [API level 35] Optional integer to use for EXTRA_ENABLE_LANGUAGE_SWITCH. If set, the language switch will be deactivated when LANGUAGE_SWITCH_MAX_SWITCHES reached.\n *\n * Depending on the recognizer implementation, this flag may have no effect.\n */\n EXTRA_LANGUAGE_SWITCH_MAX_SWITCHES: number;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_MASK_OFFENSIVE_WORDS\n *\n * [API level 33] Optional boolean indicating whether the recognizer should mask the offensive words in recognition results. The Default is true.\n *\n * Constant Value: \"android.speech.extra.MASK_OFFENSIVE_WORDS\"\n */\n EXTRA_MASK_OFFENSIVE_WORDS: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ORIGIN\n *\n * Optional value which can be used to indicate the referer url of a page in which speech was requested. For example, a web browser may choose to provide this for uses of speech on a given page.\n */\n EXTRA_ORIGIN: string;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_PREFER_OFFLINE\n *\n * Optional boolean, to be used with ACTION_RECOGNIZE_SPEECH, ACTION_VOICE_SEARCH_HANDS_FREE, ACTION_WEB_SEARCH to indicate whether to only use an offline speech recognition engine. The default is false, meaning that either network or offline recognition engines may be used.\n *\n * Depending on the recognizer implementation, these values may have no effect.\n */\n EXTRA_PREFER_OFFLINE: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_PROMPT\n *\n * Optional text prompt to show to the user when asking them to speak.\n */\n EXTRA_PROMPT: string;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_REQUEST_WORD_CONFIDENCE\n *\n * [API level 34] Optional boolean indicating whether the recognizer should return the confidence level of each word in the final recognition results.\n */\n EXTRA_REQUEST_WORD_CONFIDENCE: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_REQUEST_WORD_TIMING\n *\n * [API level 34] Optional boolean indicating whether the recognizer should return the timestamp of each word in the final recognition results.\n */\n EXTRA_REQUEST_WORD_TIMING: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_SECURE\n *\n * Optional boolean to indicate that a \"hands free\" voice search was performed while the device was in a secure mode. An example of secure mode is when the device's screen lock is active, and it requires some form of authentication to be unlocked. When the device is securely locked, the voice search activity should either restrict the set of voice actions that are permitted, or require some form of secure authentication before proceeding.\n */\n EXTRA_SECURE: boolean;\n /**\n * Optional string to enable segmented session mode of the specified type,\n * which can be `EXTRA_AUDIO_SOURCE`, `EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS` or `EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS`.\n * When segmented session mode is supported by the recognizer implementation and this extra is set,\n * it will return the recognition results in segments via [RecognitionListener#onSegmentResults(Bundle)](https://developer.android.com/reference/android/speech/RecognitionListener#onSegmentResults(android.os.Bundle))\n * and terminate the session with [RecognitionListener#onEndOfSegmentedSession()](https://developer.android.com/reference/android/speech/RecognitionListener#onEndOfSegmentedSession()).\n *\n * When setting this extra, make sure the extra used as the string value here is also set in the same intent with proper value.\n *\n * Depending on the recognizer implementation, this value may have no effect.\n */\n EXTRA_SEGMENTED_SESSION:\n | \"android.speech.extra.AUDIO_SOURCE\"\n | \"android.speech.extras.SPEECH_INPUT_MINIMUM_LENGTH_MILLIS\"\n | \"android.speech.extras.SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS\";\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS\n *\n * The amount of time that it should take after the recognizer stops hearing speech to consider the input complete hence end the recognition session.\n *\n * Note that it is extremely rare you'd want to specify this value in an intent. Generally, it should be specified only when it is also used as the value for EXTRA_SEGMENTED_SESSION to enable segmented session mode. Note also that certain values may cause undesired or unexpected results - use judiciously!\n *\n * Depending on the recognizer implementation, these values may have no effect.\n *\n */\n EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS: number;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS\n *\n * Optional integer to indicate the minimum length of the recognition session. The recognizer will not stop recognizing speech before this amount of time.\n *\n * Note that it is extremely rare you'd want to specify this value in an intent. Generally, it should be specified only when it is also used as the value for EXTRA_SEGMENTED_SESSION to enable segmented session mode. Note also that certain values may cause undesired or unexpected results - use judiciously!\n *\n * Depending on the recognizer implementation, these values may have no effect.\n */\n EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS: number;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS\n *\n * The amount of time that it should take after we stop hearing speech to consider the input possibly complete.\n * This is used to prevent the endpointer cutting off during very short mid-speech pauses.\n * Note that it is extremely rare you'd want to specify this value in an intent.\n * If you don't have a very good reason to change these, you should leave them as they are.\n * Note also that certain values may cause undesired or unexpected results - use judiciously!\n * Additionally, depending on the recognizer implementation, these values may have no effect.\n */\n EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS: number;\n};\n\nexport interface ExpoSpeechRecognitionModuleType extends NativeModule {\n /**\n * Starts speech recognition.\n */\n start(options: ExpoSpeechRecognitionOptions): void;\n /**\n * Stops speech recognition and attempts to return a final result (through the `result` event).\n */\n stop(): void;\n /**\n * Cancels speech recognition immediately without returning a final result.\n */\n abort(): void;\n /**\n * Presents a dialog to the user to request permissions for using speech recognition and the microphone.\n *\n * For iOS, once a user has granted (or denied) location permissions by responding to the original permission request dialog,\n * the only way that the permissions can be changed is by the user themselves using the device settings app.\n */\n requestPermissionsAsync(): Promise<PermissionResponse>;\n /**\n * Returns the current permission status for the microphone and speech recognition.\n */\n getPermissionsAsync(): Promise<PermissionResponse>;\n /**\n * Returns an array of locales supported by the speech recognizer.\n *\n * Not supported on Android 12 and below (API level 31), this will return an empty array of locales.\n *\n * @throws {\"package_not_found\"} If the service package is not found.\n * @throws {\"error_[number]\"} If there was an error retrieving the supported locales.\n */\n getSupportedLocales(options: {\n /**\n * The package name of the speech recognition service to use.\n *\n * e.g. \"com.google.android.as\" or \"com.samsung.android.bixby.agent\"\n *\n * Warning: the service package (such as Bixby) may not be able to return any results.\n */\n androidRecognitionServicePackage?: string;\n }): Promise<{\n /**\n * All supported languages on the device. This includes both installed and supported languages.\n */\n locales: string[];\n /**\n * These languages are installed on to the device for offline use.\n *\n * This will likely be an empty array if the service package is not \"com.google.android.as\"\n */\n installedLocales: string[];\n }>;\n /**\n * [Android only] Returns an array of package names of speech recognition services that are available on the device.\n *\n * List of all available services as bundle identifiers, e.g. [\"com.google.android.as\", \"com.google.android.tts\"]\n */\n getSpeechRecognitionServices(): string[];\n /**\n * [Android only] Returns the default voice recognition service on the device.\n *\n * @returns empty string if no service is found, or not Android\n */\n getDefaultRecognitionService(): {\n /** e.g. \"com.google.android.tts\" or \"com.google.android.googlequicksearchbox\" */\n packageName: string;\n };\n /**\n * [Android only] Returns the default voice recognition service on the device.\n *\n * e.g. \"com.google.android.googlequicksearchbox\" or \"com.samsung.android.bixby.agent\"\n *\n * @returns empty string if no service is found, or not Android\n */\n getAssistantService(): {\n /** e.g. \"com.google.android.googlequicksearchbox\" or \"com.samsung.android.bixby.agent\" */\n packageName: string;\n };\n /**\n * Whether the on-device speech recognition is available on the device.\n */\n supportsOnDeviceRecognition(): boolean;\n /**\n * Whether the recording feature is available on the device.\n *\n * This mostly applies to Android devices, to check if it's greater than Android 13.\n */\n supportsRecording(): boolean;\n /**\n * Whether on-device speech recognition is available.\n *\n * If this method returns false, `start()` will fail and emit an error event with the code `service-not-allowed` or `language-not-supported`.\n */\n isRecognitionAvailable(): boolean;\n\n /**\n * Downloads the offline model for the specified locale.\n * Note: this is only supported on Android 13 and above.\n */\n androidTriggerOfflineModelDownload(options: {\n /** The locale to download the model for, e.g. \"en-US\" */\n locale: string;\n }): Promise<{\n /**\n * On Android 13, the status will be \"opened_dialog\" indicating that the model download dialog was opened.\n * On Android 14+, the status will be \"download_success\" indicating that the model download was successful.\n * On Android 14+, \"download_canceled\" will be returned if the download was canceled by a user interaction.\n */\n status: \"download_success\" | \"opened_dialog\" | \"download_canceled\";\n message: string;\n }>;\n /**\n * [iOS only] For advanced use cases, you may use this function to set the audio session category and mode.\n *\n * See: https://developer.apple.com/documentation/avfaudio/avaudiosession/1771734-setcategory\n */\n setCategoryIOS(options: SetCategoryOptions): void;\n\n /**\n * [iOS only] Returns the current audio session category and options.\n *\n * See:\n * - [AVAudioSession.Category](https://developer.apple.com/documentation/avfaudio/avaudiosession/category)\n * - [AVAudioSession.CategoryOptions](https://developer.apple.com/documentation/avfaudio/avaudiosession/categoryoptions)\n * - [AVAudioSession.Mode](https://developer.apple.com/documentation/avfaudio/avaudiosession/mode)\n */\n getAudioSessionCategoryAndOptionsIOS(): {\n category: AVAudioSessionCategoryValue;\n categoryOptions: AVAudioSessionCategoryOptionsValue[];\n mode: AVAudioSessionModeValue;\n };\n /**\n * [iOS only] Sets the shared audio session active state.\n *\n * Calls the following on iOS: `AVAudioSession.sharedInstance().setActive(value, options)`\n *\n * See: https://developer.apple.com/documentation/avfaudio/avaudiosession/1616627-setactive\n */\n setAudioSessionActiveIOS(\n value: boolean,\n options?: {\n /** [Default: true] Whether to notify other audio sessions when the active state changes. */\n notifyOthersOnDeactivation: boolean;\n },\n ): void;\n /**\n * Returns the current state of the speech recognizer.\n */\n getStateAsync(): Promise<SpeechRecognitionState>;\n}\n\nexport type SetCategoryOptions = {\n category: AVAudioSessionCategoryValue;\n categoryOptions: AVAudioSessionCategoryOptionsValue[];\n mode?: AVAudioSessionModeValue;\n};\n\ntype SpeechRecognitionState =\n | \"inactive\"\n | \"starting\"\n | \"recognizing\"\n | \"stopping\";\n\n/**\n * [iOS only] See: [AVAudioSession.CategoryOptions](https://developer.apple.com/documentation/avfaudio/avaudiosession/categoryoptions)\n *\n * Use the `AVAudioSessionCategoryOptions` enum to get the correct value.\n */\nexport type AVAudioSessionCategoryOptionsValue =\n (typeof AVAudioSessionCategoryOptions)[keyof typeof AVAudioSessionCategoryOptions];\n\n/**\n * [iOS only] See: [AVAudioSession.Mode](https://developer.apple.com/documentation/avfaudio/avaudiosession/mode)\n *\n * Use the `AVAudioSessionMode` enum to get the correct value.\n */\nexport type AVAudioSessionModeValue =\n (typeof AVAudioSessionMode)[keyof typeof AVAudioSessionMode];\n"]}
1
+ {"version":3,"file":"ExpoSpeechRecognitionModule.types.js","sourceRoot":"","sources":["../src/ExpoSpeechRecognitionModule.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { PermissionResponse } from \"expo-modules-core\";\nimport type { NativeModule } from \"expo\";\n\nimport type {\n AudioEncodingAndroid,\n AVAudioSessionCategory,\n AVAudioSessionCategoryOptions,\n AVAudioSessionMode,\n RecognizerIntentEnableLanguageSwitch,\n RecognizerIntentExtraLanguageModel,\n TaskHintIOS,\n} from \"./constants\";\n\nexport type AVAudioSessionCategoryValue =\n (typeof AVAudioSessionCategory)[keyof typeof AVAudioSessionCategory];\n\nexport type ExpoSpeechRecognitionResult = {\n transcript: string;\n /**\n * Value ranging between between 0.0, 1.0, and -1 (unavailable) indicating transcript confidence.\n */\n confidence: number;\n /**\n * An array of transcription segments that represent the parts of the transcription, as identified by the speech recognizer.\n *\n * Notes for Android:\n *\n * - This is only available for SDK 34+ (Android 14+)\n * - This is only verified to work with the `com.google.android.as` service (using on device speech recognition)\n * - Segments are only available during the final result\n * - The segment parts are split up by words.\n * - The segments are only available for the first transcript\n * - Segment confidences currently return as -1 (unavailable)\n *\n * Notes for iOS:\n *\n * - The confidence value will be 0 on partial results\n */\n segments: ExpoSpeechRecognitionResultSegment[];\n};\n\nexport type ExpoSpeechRecognitionResultSegment = {\n /** The start timestamp of the utterance, e.g. 1000 */\n startTimeMillis: number;\n /** The end timestamp of the utterance, e.g. 1500 */\n endTimeMillis: number;\n /** The text portion of the transcript, e.g. \"Hello world\" */\n segment: string;\n /** Value ranging between between 0.0, 1.0, and -1 (unavailable) indicating the confidence of the specific segment */\n confidence: number;\n};\n\n/** Fired when there's a speech result. The result may be partial or final */\nexport type ExpoSpeechRecognitionResultEvent = {\n isFinal: boolean;\n results: ExpoSpeechRecognitionResult[];\n};\n\nexport type ExpoSpeechRecognitionErrorCode =\n /** The user called `ExpoSpeechRecognitionModule.abort()`. */\n | \"aborted\"\n /** Audio recording error. */\n | \"audio-capture\"\n /** There was an error in the speech recognition grammar or semantic tags, or the chosen grammar format or semantic tag format was unsupported. */\n | \"bad-grammar\"\n /** Locale is not supported by the speech recognizer. */\n | \"language-not-supported\"\n /** Network communication required for completing the recognition failed. */\n | \"network\"\n /** No final speech was detected. */\n | \"no-speech\"\n /** Permission to use speech recognition or microphone was not granted. */\n | \"not-allowed\"\n /** Recognizer is unavailable. */\n | \"service-not-allowed\"\n // Extra codes (not part of the spec)\n /** The recognizer is busy and cannot accept any new recognition requests. */\n | \"busy\"\n /** (Android only) An unknown client-side error occurred. */\n | \"client\"\n /** (Android) No speech input. */\n | \"speech-timeout\"\n /** (Android) Unknown error */\n | \"unknown\";\n\nexport type ExpoSpeechRecognitionErrorEvent = {\n error: ExpoSpeechRecognitionErrorCode;\n message: string;\n};\n\nexport type LanguageDetectionEvent = {\n /** The language that was detected, in BCP-47 format. e.g. \"en-US\", \"de-DE\" */\n detectedLanguage: string;\n /** The confidence of the detected language. A value ranging between 0.0 and 1.0.\n *\n * Values range from:\n *\n * - 1.0 (highly confident)\n * - 0.8 (confident)\n * - 0.5 (not confident)\n * - 0.0 (unknown)\n */\n confidence: number;\n /** The alternative locales for the same language, in BCP-47 format. e.g. [\"en-US\", \"en-GB\"] */\n topLocaleAlternatives: string[];\n};\n\n/**\n * Events that are dispatched from the native side\n */\nexport type ExpoSpeechRecognitionNativeEventMap = {\n result: ExpoSpeechRecognitionResultEvent;\n error: ExpoSpeechRecognitionErrorEvent;\n start: null;\n speechstart: null;\n speechend: null;\n /** A final result is returned with no significant recognition */\n nomatch: null;\n /** Audio capturing had started */\n audiostart: {\n /**\n * The uri is set when `recordingOptions.persist` is enabled.\n * Do not attempt to use this file until the `audioend` event is emitted.\n *\n * Example URIs:\n *\n * - Android: `file:///data/user/0/expo.modules.speechrecognition.example/cache/recording_1720678500903.wav`\n * - iOS: `file:///path/to/Library/Caches/audio_CD5E6C6C-3D9D-4754-9188-D6FAF97D9DF2.caf`\n */\n uri: string | null;\n };\n /** Audio capturing had ended */\n audioend: {\n /**\n * The uri is set when `recordingOptions.persist` is enabled.\n *\n * Example URIs:\n *\n * - Android: `file:///data/user/0/expo.modules.speechrecognition.example/cache/recording_1720678500903.wav`\n * - iOS: `file:///path/to/Library/Caches/audio_CD5E6C6C-3D9D-4754-9188-D6FAF97D9DF2.caf`\n */\n uri: string | null;\n };\n end: null;\n soundstart: null;\n soundend: null;\n languagedetection: LanguageDetectionEvent;\n volumechange: {\n /**\n * A float value between -2 and 10 indicating the volume of the input audio\n *\n * Consider anything below 0 to be inaudible\n */\n value: number;\n };\n};\n\nexport type ExpoSpeechRecognitionOptions = {\n /** [Default: \"en-US\"] The language of the speech recognition */\n lang?: string;\n /** [Default: false] Note for iOS: final results are only available after speech recognition has stopped */\n interimResults?: boolean;\n /** [Default: 5] The maximum number of alternative transcriptions to return. */\n maxAlternatives?: number;\n /**\n * An array of strings that will be used to provide context to the speech recognition engine.\n *\n * On Android, this configures [`EXTRA_BIASING_STRINGS`](https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_BIASING_STRINGS) in the recognizer intent (API level 33+).\n *\n * On iOS, this configures [`SFSpeechRecognitionRequest.contextualStrings`](https://developer.apple.com/documentation/speech/sfspeechrecognitionrequest/1649391-contextualstrings).\n */\n contextualStrings?: string[];\n /**\n * [Default: false] Continuous recognition.\n *\n * Not supported on Android 12 and below.\n *\n * If false, the behaviors are the following:\n *\n * - on iOS 17-, recognition will run until no speech is detected for 3 seconds.\n * - on iOS 18+ and Android, recognition will run until a result with `isFinal: true` is received.\n */\n continuous?: boolean;\n /** [Default: false] Prevent device from sending audio over the network. Only enabled if the device supports it.\n *\n * Use `getSupportedLocales()` to verify if the locale is installed on the device prior to enabling this option.\n */\n requiresOnDeviceRecognition?: boolean;\n /**\n * [Default: false] Include punctuation in the recognition results. This applies to full stops and commas.\n *\n * On Android, this configures [`EXTRA_ENABLE_FORMATTING`](https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_FORMATTING) in the recognizer intent (Android 13+, API level 33+).\n *\n * Note for Android: This feature is only verified to work on Android 13+ with on-device speech recognition enabled (i.e. enabling `requiresOnDeviceRecognition` or using the `com.google.android.as` service package)\n *\n * On iOS, this configures [`SFSpeechRecognitionRequest.addsPunctuation`](https://developer.apple.com/documentation/speech/sfspeechrecognitionrequest/3930023-addspunctuation).\n */\n addsPunctuation?: boolean;\n /**\n * The package name of the speech recognition service to use.\n * If not provided, the default service will be used.\n *\n * Obtain the supported packages by running `ExpoSpeechRecognitionModule.getSpeechRecognitionServices()`\n *\n * e.g. \"com.google.android.as\" or \"com.samsung.android.bixby.agent\"\n */\n androidRecognitionServicePackage?: string;\n /**\n * Extra options to provide to the Android Recognition intent.\n *\n * For a full list of options, see https://developer.android.com/reference/android/speech/RecognizerIntent\n */\n androidIntentOptions?: Partial<AndroidIntentOptions>;\n /**\n * Audio source options to pass to the recognizer.\n *\n * This option can be used to recognize audio from a local or remote file URI.\n */\n audioSource?: AudioSourceOptions;\n /**\n * Audio recording options for persisting the audio to a local file path.\n */\n recordingOptions?: RecordingOptions;\n /**\n * Default: `\"android.speech.action.RECOGNIZE_SPEECH\"`\n *\n * The kind of intent action\n *\n * Intents:\n *\n * - [`android.speech.action.RECOGNIZE_SPEECH`](https://developer.android.com/reference/android/speech/RecognizerIntent#ACTION_RECOGNIZE_SPEECH) which performs speech recognition (default)\n * - [`android.speech.action.VOICE_SEARCH_HANDS_FREE`](https://developer.android.com/reference/android/speech/RecognizerIntent#ACTION_VOICE_SEARCH_HANDS_FREE) - prompts the user for speech without requiring the user's visual attention or touch input\n * - [`android.speech.action.WEB_SEARCH`](https://developer.android.com/reference/android/speech/RecognizerIntent#ACTION_WEB_SEARCH) - displays a web search result or trigger another type of action based on the user's speech.\n */\n androidIntent?:\n | \"android.speech.action.RECOGNIZE_SPEECH\"\n | \"android.speech.action.VOICE_SEARCH_HANDS_FREE\"\n | \"android.speech.action.WEB_SEARCH\";\n\n /**\n * The hint for the speech recognition task.\n *\n * Default: `\"unspecified\"`\n *\n * Docs: https://developer.apple.com/documentation/speech/sfspeechrecognitiontaskhint\n */\n iosTaskHint?: IOSTaskHintValue;\n\n /**\n * The audio category for the speech recognition task.\n *\n * Use this option to configure the default audio session category and mode prior to starting speech recognition.\n *\n * **Caution:** confirm that the category, options and mode are compatible with the audio source.\n *\n * By default, the audio session category and mode are set to:\n *\n * - category: `playAndRecord`\n * - options: `defaultToSpeaker` and `allowBluetooth`\n * - mode: `measurement`\n *\n * Docs: https://developer.apple.com/documentation/avfaudio/avaudiosession/category\n */\n iosCategory?: SetCategoryOptions;\n\n /**\n * Settings for volume change events.\n */\n volumeChangeEventOptions?: {\n /**\n * Whether to emit volume change events.\n *\n * Default: false\n */\n enabled?: boolean;\n /**\n * Specifies the interval (in milliseconds) to emit `volumechange` events.\n *\n * Default: 100ms on iOS\n *\n * Increasing this value will improve performance\n */\n intervalMillis?: number;\n };\n};\n\nexport type IOSTaskHintValue = (typeof TaskHintIOS)[keyof typeof TaskHintIOS];\n\nexport type RecordingOptions = {\n /**\n * Whether to persist the audio to a local file path.\n *\n * Default: false\n */\n persist: boolean;\n /**\n * Default: `FileSystem.CacheDirectory`. This changes the default storage location for the audio file.\n */\n outputDirectory?: string;\n /**\n * Default: `\"recording_${timestamp|uuid}.[wav|caf]\"`. This changes the file name for the audio file.\n */\n outputFileName?: string;\n /**\n * Default: undefined. The sample rate of the output audio file.\n *\n * Only supported on iOS\n *\n * Default sample rate is: 16000 on Android, 44100/48000 on iOS\n */\n outputSampleRate?: number;\n /**\n * Default: undefined. The encoding of the output audio file.\n *\n * Only supported on iOS\n */\n outputEncoding?:\n | \"pcmFormatFloat32\"\n | \"pcmFormatFloat64\"\n | \"pcmFormatInt16\"\n | \"pcmFormatInt32\";\n};\n\nexport type AudioSourceOptions = {\n /**\n * Local audio source URI.\n *\n * e.g. `\"file:///storage/emulated/0/Download/audio.wav\"`\n */\n uri: string;\n /**\n * [Android only] The number of channels in the source audio.\n *\n * Default: 1\n */\n audioChannels?: number;\n /**\n * [Android only] A value from [AudioFormat](https://developer.android.com/reference/android/media/AudioFormat).\n *\n * Use the `AudioEncodingAndroid` enum to get the correct value.\n */\n audioEncoding?: AudioEncodingAndroidValue;\n /**\n * [Android only] Audio sampling rate in Hz.\n *\n * Default: 16000\n */\n sampleRate?: number;\n /**\n * [Android only] The delay for a 4KiB chunk of audio to stream to the speech recognition service.\n *\n * Use this setting to avoid being rate-limited when using network-based recognition.\n *\n * If you're using on-device recognition, you may want to increase this value to avoid unprocessed audio chunks.\n *\n * Default: 50ms for network-based recognition, 15ms for on-device recognition\n */\n chunkDelayMillis?: number;\n};\n\nexport type AudioEncodingAndroidValue =\n (typeof AudioEncodingAndroid)[keyof typeof AudioEncodingAndroid];\n\nexport type AndroidIntentOptions = {\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_CALLING_PACKAGE\n *\n * The extra key used in an intent to the speech recognizer for voice search. Not generally to be used by developers. The system search dialog uses this, for example, to set a calling package for identification by a voice search API. If this extra is set by anyone but the system process, it should be overridden by the voice search implementation.\n */\n EXTRA_CALLING_PACKAGE: string;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_BIASING_DEVICE_CONTEXT\n *\n * Optional boolean to enable biasing towards device context. The recognizer will use the device context to tune the recognition results.\n *\n * Depending on the recognizer implementation, this value may have no effect.\n */\n EXTRA_ENABLE_BIASING_DEVICE_CONTEXT: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_LANGUAGE_DETECTION\n *\n * Optional boolean indicating whether to enable language detection. When enabled, the recognizer will consistently identify the language of the current spoken utterance and provide that info via RecognitionListener#onLanguageDetection(Bundle).\n */\n EXTRA_ENABLE_LANGUAGE_DETECTION: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_LANGUAGE_SWITCH\n *\n * Optional string to enable automatic switching to the language being spoken with the desired sensitivity level, instead of being restricted to a single language. The corresponding language models must be downloaded to support the switch. Otherwise, the recognizer will report an error on a switch failure. The recognizer provides the switch results via RecognitionListener#onLanguageDetection(Bundle).\n *\n * Since detection is a necessary requirement for the language switching, setting this value implicitly enables EXTRA_ENABLE_LANGUAGE_DETECTION.\n *\n * Depending on the recognizer implementation, this value may have no effect.\n */\n EXTRA_ENABLE_LANGUAGE_SWITCH: (typeof RecognizerIntentEnableLanguageSwitch)[keyof typeof RecognizerIntentEnableLanguageSwitch];\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_FORMATTING\n *\n * NOTE: This is also configurable through `addsPunctuation` (which sets `EXTRA_ENABLE_FORMATTING` to \"quality\")\n *\n * [API level 33] Optional string to enable text formatting (e.g. unspoken punctuation (examples: question mark, comma, period, etc.), capitalization, etc.) and specify the optimization strategy. If set, the partial and final result texts will be formatted. Each result list will contain two hypotheses in the order of 1) formatted text 2) raw text.\n *\n */\n EXTRA_ENABLE_FORMATTING: \"latency\" | \"quality\";\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_HIDE_PARTIAL_TRAILING_PUNCTUATION\n *\n * [API level 33] Optional boolean, to be used with EXTRA_ENABLE_FORMATTING, to prevent the recognizer adding punctuation after the last word of the partial results. The default is false.\n */\n EXTRA_HIDE_PARTIAL_TRAILING_PUNCTUATION: boolean;\n /**\n * Optional list of IETF language tags (as defined by BCP 47, e.g. \"en-US\", \"de-DE\").\n *\n * [API level 34] This extra is to be used with EXTRA_ENABLE_LANGUAGE_DETECTION. If set, the recognizer will constrain the language detection output to this list of languages, potentially improving detection accuracy.\n */\n EXTRA_LANGUAGE_DETECTION_ALLOWED_LANGUAGES: string[];\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_LANGUAGE_MODEL\n *\n * [Default: free_form] The language model to use for speech recognition.\n *\n * Informs the recognizer which speech model to prefer when performing ACTION_RECOGNIZE_SPEECH.\n * The recognizer uses this information to fine tune the results.\n * This extra is required. Activities implementing ACTION_RECOGNIZE_SPEECH may interpret the values as they see fit.\n */\n EXTRA_LANGUAGE_MODEL: (typeof RecognizerIntentExtraLanguageModel)[keyof typeof RecognizerIntentExtraLanguageModel];\n\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_LANGUAGE_SWITCH_ALLOWED_LANGUAGES\n *\n * [API level 34] Optional list of IETF language tags (as defined by BCP 47, e.g. \"en-US\", \"de-DE\").\n * This extra is to be used with EXTRA_ENABLE_LANGUAGE_SWITCH. If set, the recognizer will apply the auto switch only to these languages, even if the speech models of other languages also exist.\n * The corresponding language models must be downloaded to support the switch. Otherwise, the recognizer will report an error on a switch failure.\n */\n EXTRA_LANGUAGE_SWITCH_ALLOWED_LANGUAGES: string[];\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_LANGUAGE_SWITCH_INITIAL_ACTIVE_DURATION_TIME_MILLIS\n *\n * [API level 35] Optional integer to use for EXTRA_ENABLE_LANGUAGE_SWITCH. If set, the language switch will only be activated for this value of ms of audio since the START_OF_SPEECH. This could provide a more stable recognition result when the language switch is only required in the beginning of the session.\n */\n EXTRA_LANGUAGE_SWITCH_INITIAL_ACTIVE_DURATION_TIME_MILLIS: number;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_LANGUAGE_SWITCH_MAX_SWITCHES\n *\n * [API level 35] Optional integer to use for EXTRA_ENABLE_LANGUAGE_SWITCH. If set, the language switch will be deactivated when LANGUAGE_SWITCH_MAX_SWITCHES reached.\n *\n * Depending on the recognizer implementation, this flag may have no effect.\n */\n EXTRA_LANGUAGE_SWITCH_MAX_SWITCHES: number;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_MASK_OFFENSIVE_WORDS\n *\n * [API level 33] Optional boolean indicating whether the recognizer should mask the offensive words in recognition results. The Default is true.\n *\n * Constant Value: \"android.speech.extra.MASK_OFFENSIVE_WORDS\"\n */\n EXTRA_MASK_OFFENSIVE_WORDS: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ORIGIN\n *\n * Optional value which can be used to indicate the referer url of a page in which speech was requested. For example, a web browser may choose to provide this for uses of speech on a given page.\n */\n EXTRA_ORIGIN: string;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_PREFER_OFFLINE\n *\n * Optional boolean, to be used with ACTION_RECOGNIZE_SPEECH, ACTION_VOICE_SEARCH_HANDS_FREE, ACTION_WEB_SEARCH to indicate whether to only use an offline speech recognition engine. The default is false, meaning that either network or offline recognition engines may be used.\n *\n * Depending on the recognizer implementation, these values may have no effect.\n */\n EXTRA_PREFER_OFFLINE: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_PROMPT\n *\n * Optional text prompt to show to the user when asking them to speak.\n */\n EXTRA_PROMPT: string;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_REQUEST_WORD_CONFIDENCE\n *\n * [API level 34] Optional boolean indicating whether the recognizer should return the confidence level of each word in the final recognition results.\n */\n EXTRA_REQUEST_WORD_CONFIDENCE: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_REQUEST_WORD_TIMING\n *\n * [API level 34] Optional boolean indicating whether the recognizer should return the timestamp of each word in the final recognition results.\n */\n EXTRA_REQUEST_WORD_TIMING: boolean;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_SECURE\n *\n * Optional boolean to indicate that a \"hands free\" voice search was performed while the device was in a secure mode. An example of secure mode is when the device's screen lock is active, and it requires some form of authentication to be unlocked. When the device is securely locked, the voice search activity should either restrict the set of voice actions that are permitted, or require some form of secure authentication before proceeding.\n */\n EXTRA_SECURE: boolean;\n /**\n * Optional string to enable segmented session mode of the specified type,\n * which can be `EXTRA_AUDIO_SOURCE`, `EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS` or `EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS`.\n * When segmented session mode is supported by the recognizer implementation and this extra is set,\n * it will return the recognition results in segments via [RecognitionListener#onSegmentResults(Bundle)](https://developer.android.com/reference/android/speech/RecognitionListener#onSegmentResults(android.os.Bundle))\n * and terminate the session with [RecognitionListener#onEndOfSegmentedSession()](https://developer.android.com/reference/android/speech/RecognitionListener#onEndOfSegmentedSession()).\n *\n * When setting this extra, make sure the extra used as the string value here is also set in the same intent with proper value.\n *\n * Depending on the recognizer implementation, this value may have no effect.\n */\n EXTRA_SEGMENTED_SESSION:\n | \"android.speech.extra.AUDIO_SOURCE\"\n | \"android.speech.extras.SPEECH_INPUT_MINIMUM_LENGTH_MILLIS\"\n | \"android.speech.extras.SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS\";\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS\n *\n * The amount of time that it should take after the recognizer stops hearing speech to consider the input complete hence end the recognition session.\n *\n * Note that it is extremely rare you'd want to specify this value in an intent. Generally, it should be specified only when it is also used as the value for EXTRA_SEGMENTED_SESSION to enable segmented session mode. Note also that certain values may cause undesired or unexpected results - use judiciously!\n *\n * Depending on the recognizer implementation, these values may have no effect.\n *\n */\n EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS: number;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS\n *\n * Optional integer to indicate the minimum length of the recognition session. The recognizer will not stop recognizing speech before this amount of time.\n *\n * Note that it is extremely rare you'd want to specify this value in an intent. Generally, it should be specified only when it is also used as the value for EXTRA_SEGMENTED_SESSION to enable segmented session mode. Note also that certain values may cause undesired or unexpected results - use judiciously!\n *\n * Depending on the recognizer implementation, these values may have no effect.\n */\n EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS: number;\n /**\n * https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS\n *\n * The amount of time that it should take after we stop hearing speech to consider the input possibly complete.\n * This is used to prevent the endpointer cutting off during very short mid-speech pauses.\n * Note that it is extremely rare you'd want to specify this value in an intent.\n * If you don't have a very good reason to change these, you should leave them as they are.\n * Note also that certain values may cause undesired or unexpected results - use judiciously!\n * Additionally, depending on the recognizer implementation, these values may have no effect.\n */\n EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS: number;\n};\n\nexport type ExpoSpeechRecognitionNativeEvents = {\n [K in keyof ExpoSpeechRecognitionNativeEventMap]: (\n event: ExpoSpeechRecognitionNativeEventMap[K],\n ) => void;\n};\n\nexport declare class ExpoSpeechRecognitionModuleType extends NativeModule<ExpoSpeechRecognitionNativeEvents> {\n /**\n * Starts speech recognition.\n */\n start(options: ExpoSpeechRecognitionOptions): void;\n /**\n * Stops speech recognition and attempts to return a final result (through the `result` event).\n */\n stop(): void;\n /**\n * Cancels speech recognition immediately without returning a final result.\n */\n abort(): void;\n /**\n * Presents a dialog to the user to request permissions for using speech recognition and the microphone.\n *\n * For iOS, once a user has granted (or denied) location permissions by responding to the original permission request dialog,\n * the only way that the permissions can be changed is by the user themselves using the device settings app.\n */\n requestPermissionsAsync(): Promise<PermissionResponse>;\n /**\n * Returns the current permission status for the microphone and speech recognition.\n */\n getPermissionsAsync(): Promise<PermissionResponse>;\n /**\n * Returns an array of locales supported by the speech recognizer.\n *\n * Not supported on Android 12 and below (API level 31), this will return an empty array of locales.\n *\n * @throws {\"package_not_found\"} If the service package is not found.\n * @throws {\"error_[number]\"} If there was an error retrieving the supported locales.\n */\n getSupportedLocales(options: {\n /**\n * The package name of the speech recognition service to use.\n *\n * e.g. \"com.google.android.as\" or \"com.samsung.android.bixby.agent\"\n *\n * Warning: the service package (such as Bixby) may not be able to return any results.\n */\n androidRecognitionServicePackage?: string;\n }): Promise<{\n /**\n * All supported languages on the device. This includes both installed and supported languages.\n */\n locales: string[];\n /**\n * These languages are installed on to the device for offline use.\n *\n * This will likely be an empty array if the service package is not \"com.google.android.as\"\n */\n installedLocales: string[];\n }>;\n /**\n * [Android only] Returns an array of package names of speech recognition services that are available on the device.\n *\n * List of all available services as bundle identifiers, e.g. [\"com.google.android.as\", \"com.google.android.tts\"]\n */\n getSpeechRecognitionServices(): string[];\n /**\n * [Android only] Returns the default voice recognition service on the device.\n *\n * @returns empty string if no service is found, or not Android\n */\n getDefaultRecognitionService(): {\n /** e.g. \"com.google.android.tts\" or \"com.google.android.googlequicksearchbox\" */\n packageName: string;\n };\n /**\n * [Android only] Returns the default voice recognition service on the device.\n *\n * e.g. \"com.google.android.googlequicksearchbox\" or \"com.samsung.android.bixby.agent\"\n *\n * @returns empty string if no service is found, or not Android\n */\n getAssistantService(): {\n /** e.g. \"com.google.android.googlequicksearchbox\" or \"com.samsung.android.bixby.agent\" */\n packageName: string;\n };\n /**\n * Whether the on-device speech recognition is available on the device.\n */\n supportsOnDeviceRecognition(): boolean;\n /**\n * Whether the recording feature is available on the device.\n *\n * This mostly applies to Android devices, to check if it's greater than Android 13.\n */\n supportsRecording(): boolean;\n /**\n * Whether on-device speech recognition is available.\n *\n * If this method returns false, `start()` will fail and emit an error event with the code `service-not-allowed` or `language-not-supported`.\n */\n isRecognitionAvailable(): boolean;\n\n /**\n * Downloads the offline model for the specified locale.\n * Note: this is only supported on Android 13 and above.\n */\n androidTriggerOfflineModelDownload(options: {\n /** The locale to download the model for, e.g. \"en-US\" */\n locale: string;\n }): Promise<{\n /**\n * On Android 13, the status will be \"opened_dialog\" indicating that the model download dialog was opened.\n * On Android 14+, the status will be \"download_success\" indicating that the model download was successful.\n * On Android 14+, \"download_canceled\" will be returned if the download was canceled by a user interaction.\n */\n status: \"download_success\" | \"opened_dialog\" | \"download_canceled\";\n message: string;\n }>;\n /**\n * [iOS only] For advanced use cases, you may use this function to set the audio session category and mode.\n *\n * See: https://developer.apple.com/documentation/avfaudio/avaudiosession/1771734-setcategory\n */\n setCategoryIOS(options: SetCategoryOptions): void;\n\n /**\n * [iOS only] Returns the current audio session category and options.\n *\n * See:\n * - [AVAudioSession.Category](https://developer.apple.com/documentation/avfaudio/avaudiosession/category)\n * - [AVAudioSession.CategoryOptions](https://developer.apple.com/documentation/avfaudio/avaudiosession/categoryoptions)\n * - [AVAudioSession.Mode](https://developer.apple.com/documentation/avfaudio/avaudiosession/mode)\n */\n getAudioSessionCategoryAndOptionsIOS(): {\n category: AVAudioSessionCategoryValue;\n categoryOptions: AVAudioSessionCategoryOptionsValue[];\n mode: AVAudioSessionModeValue;\n };\n /**\n * [iOS only] Sets the shared audio session active state.\n *\n * Calls the following on iOS: `AVAudioSession.sharedInstance().setActive(value, options)`\n *\n * See: https://developer.apple.com/documentation/avfaudio/avaudiosession/1616627-setactive\n */\n setAudioSessionActiveIOS(\n value: boolean,\n options?: {\n /** [Default: true] Whether to notify other audio sessions when the active state changes. */\n notifyOthersOnDeactivation: boolean;\n },\n ): void;\n /**\n * Returns the current state of the speech recognizer.\n */\n getStateAsync(): Promise<SpeechRecognitionState>;\n}\n\nexport type SetCategoryOptions = {\n category: AVAudioSessionCategoryValue;\n categoryOptions: AVAudioSessionCategoryOptionsValue[];\n mode?: AVAudioSessionModeValue;\n};\n\ntype SpeechRecognitionState =\n | \"inactive\"\n | \"starting\"\n | \"recognizing\"\n | \"stopping\";\n\n/**\n * [iOS only] See: [AVAudioSession.CategoryOptions](https://developer.apple.com/documentation/avfaudio/avaudiosession/categoryoptions)\n *\n * Use the `AVAudioSessionCategoryOptions` enum to get the correct value.\n */\nexport type AVAudioSessionCategoryOptionsValue =\n (typeof AVAudioSessionCategoryOptions)[keyof typeof AVAudioSessionCategoryOptions];\n\n/**\n * [iOS only] See: [AVAudioSession.Mode](https://developer.apple.com/documentation/avfaudio/avaudiosession/mode)\n *\n * Use the `AVAudioSessionMode` enum to get the correct value.\n */\nexport type AVAudioSessionModeValue =\n (typeof AVAudioSessionMode)[keyof typeof AVAudioSessionMode];\n"]}
@@ -1,12 +1,45 @@
1
- import type { ExpoSpeechRecognitionModuleType, ExpoSpeechRecognitionNativeEventMap } from "./ExpoSpeechRecognitionModule.types";
2
- export declare const ExpoSpeechRecognitionModule: ExpoSpeechRecognitionModuleType;
3
- export declare const ExpoSpeechRecognitionModuleEmitter: {
4
- _nativeListeners: Map<string, Set<(event: any) => void>>;
5
- _clientListeners: Map<(event: any) => void, (event: any) => void>;
6
- addListener<T extends keyof SpeechRecognitionEventMap>(eventName: T, listener: (ev: ExpoSpeechRecognitionNativeEventMap[T]) => void): {
7
- remove: () => void;
1
+ import type { EventSubscription, PermissionResponse } from "expo-modules-core";
2
+ import { NativeModule } from "expo";
3
+ import type { ExpoSpeechRecognitionNativeEventMap, ExpoSpeechRecognitionNativeEvents, ExpoSpeechRecognitionOptions } from "./ExpoSpeechRecognitionModule.types";
4
+ type NativeEventListener = (event: SpeechRecognitionEventMap[keyof SpeechRecognitionEventMap]) => void;
5
+ declare class ExpoSpeechRecognitionModuleWeb extends NativeModule<ExpoSpeechRecognitionNativeEvents> {
6
+ _clientListeners: Map<ExpoSpeechRecognitionNativeEvents[keyof ExpoSpeechRecognitionNativeEvents], NativeEventListener>;
7
+ _nativeListeners: Map<string, Set<NativeEventListener>>;
8
+ bindEventListener: <T extends keyof SpeechRecognitionEventMap>(eventName: T, ev: SpeechRecognitionEventMap[T]) => void;
9
+ addListener<EventName extends keyof ExpoSpeechRecognitionNativeEventMap>(eventName: EventName, listener: ExpoSpeechRecognitionNativeEvents[EventName]): EventSubscription;
10
+ removeAllListeners(eventName: keyof ExpoSpeechRecognitionNativeEventMap): void;
11
+ start(options: ExpoSpeechRecognitionOptions): void;
12
+ getStateAsync(): Promise<string>;
13
+ stop(): void;
14
+ abort(): void;
15
+ requestPermissionsAsync(): Promise<PermissionResponse>;
16
+ getPermissionsAsync(): Promise<PermissionResponse>;
17
+ getSupportedLocales(): Promise<{
18
+ locales: string[];
19
+ installedLocales: string[];
20
+ }>;
21
+ getSpeechRecognitionServices(): string[];
22
+ getDefaultRecognitionService(): {
23
+ packageName: string;
8
24
  };
9
- removeListener: (eventName: string, listener: (event: any) => void) => void;
10
- removeAllListeners: (eventName: string) => void;
11
- };
25
+ getAssistantService(): {
26
+ packageName: string;
27
+ };
28
+ supportsOnDeviceRecognition(): boolean;
29
+ supportsRecording(): boolean;
30
+ androidTriggerOfflineModelDownload(): Promise<{
31
+ status: string;
32
+ message: string;
33
+ }>;
34
+ setCategoryIOS(): void;
35
+ getAudioSessionCategoryAndOptionsIOS(): {
36
+ category: string;
37
+ categoryOptions: string[];
38
+ mode: string;
39
+ };
40
+ setAudioSessionActiveIOS(): void;
41
+ isRecognitionAvailable(): boolean;
42
+ }
43
+ export declare const ExpoSpeechRecognitionModule: typeof ExpoSpeechRecognitionModuleWeb;
44
+ export {};
12
45
  //# sourceMappingURL=ExpoSpeechRecognitionModule.web.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ExpoSpeechRecognitionModule.web.d.ts","sourceRoot":"","sources":["../src/ExpoSpeechRecognitionModule.web.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,+BAA+B,EAC/B,mCAAmC,EACpC,MAAM,qC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F,WAAW,CAAC,SAAS,SAAS,MAAM,mCAAmC,EACrE,SAAS,EAAE,SAAS,EACpB,QAAQ,EAAE,iCAAiC,CAAC,SAAS,CAAC,GACrD,iBAAiB;IAyCpB,kBAAkB,CAChB,SAAS,EAAE,MAAM,mCAAmC,GACnD,IAAI;IA4BP,KAAK,CAAC,OAAO,EAAE,4BAA4B;IAyB3C,aAAa;IAOb,IAAI;IAGJ,KAAK;IAIL,uBAAuB;IASvB,mBAAmB;IAYb,mBAAmB;iBAKN,MAAM,EAAE;0BACC,MAAM,EAAE;;IAQpC,4BAA4B,IACb,MAAM,EAAE;IAGvB,4BAA4B;;;IAM5B,mBAAmB;;;IAMnB,2BAA2B;IAI3B,iBAAiB;IAIjB,kCAAkC;;;;IAUlC,cAAc;IAId,oCAAoC;;;;;IAWpC,wBAAwB;IAIxB,sBAAsB;CAOvB;AAwCD,eAAO,MAAM,2BAA2B,uCAEvC,CAAC"}
@@ -1,8 +1,75 @@
1
+ import { registerWebModule, NativeModule } from "expo";
1
2
  let _speechRecognitionRef = null;
2
3
  // It loads the native module object from the JSI or falls back to
3
4
  // the bridge module (from NativeModulesProxy) if the remote debugger is on.
4
- export const ExpoSpeechRecognitionModule = {
5
- start: (options) => {
5
+ class ExpoSpeechRecognitionModuleWeb extends NativeModule {
6
+ _clientListeners = new Map();
7
+ _nativeListeners = new Map();
8
+ // Convert the web event to the native event
9
+ bindEventListener = (eventName, ev) => {
10
+ const eventPayload = webToNativeEventMap[eventName]?.(ev);
11
+ this.emit(eventName,
12
+ // @ts-expect-error payload typings are incorrect
13
+ eventPayload);
14
+ };
15
+ addListener(eventName, listener) {
16
+ // Convert the web event to the native event
17
+ // @ts-expect-error Not all events are covered here
18
+ const nativeListener = (ev) => {
19
+ const handler = eventName in webToNativeEventMap
20
+ ? webToNativeEventMap[eventName]
21
+ : null;
22
+ // @ts-expect-error payload typings are incorrect
23
+ const eventPayload = handler?.(ev);
24
+ // @ts-expect-error
25
+ listener(eventPayload);
26
+ };
27
+ // @ts-expect-error
28
+ _speechRecognitionRef?.addEventListener(eventName, nativeListener);
29
+ if (!this._nativeListeners.has(eventName)) {
30
+ this._nativeListeners.set(eventName, new Set());
31
+ }
32
+ // Add the original listener to the enhanced listeners
33
+ // @ts-expect-error
34
+ this._nativeListeners.get(eventName)?.add(nativeListener);
35
+ // Map the original listener to the enhanced listener
36
+ // @ts-expect-error
37
+ this._clientListeners.set(listener, nativeListener);
38
+ const handle = super.addListener(eventName, listener);
39
+ return {
40
+ remove: () => {
41
+ // @ts-expect-error
42
+ this._nativeListeners.get(eventName)?.delete(nativeListener);
43
+ this._clientListeners.delete(listener);
44
+ handle.remove();
45
+ },
46
+ };
47
+ }
48
+ removeAllListeners(eventName) {
49
+ // Go through _listeners and remove all listeners for this event
50
+ if (this._nativeListeners.has(eventName)) {
51
+ const nativeListeners = this._nativeListeners.get(eventName);
52
+ if (!nativeListeners) {
53
+ return;
54
+ }
55
+ // Remove the enhanced listeners
56
+ for (const [listener, nativeListener] of this._clientListeners) {
57
+ // if nativeListener in listeners, remove it
58
+ if (nativeListeners.has(nativeListener)) {
59
+ // Remove the enhanced listener
60
+ this.removeListener(eventName, listener);
61
+ }
62
+ }
63
+ // ...and the native listeners
64
+ for (const listener of nativeListeners) {
65
+ // @ts-expect-error
66
+ this.removeListener(eventName, listener);
67
+ }
68
+ // Clean up
69
+ this._nativeListeners.delete(eventName);
70
+ }
71
+ }
72
+ start(options) {
6
73
  const SpeechRecognitionClass = typeof webkitSpeechRecognition !== "undefined"
7
74
  ? webkitSpeechRecognition
8
75
  : SpeechRecognition;
@@ -13,7 +80,7 @@ export const ExpoSpeechRecognitionModule = {
13
80
  _speechRecognitionRef.continuous = options.continuous ?? false;
14
81
  // Re-subscribe to events so that we don't lose them
15
82
  // This covers the case where the user has already subscribed to an event prior to calling `start()`
16
- ExpoSpeechRecognitionModuleEmitter._nativeListeners.forEach((listeners, eventName) => {
83
+ this._nativeListeners.forEach((listeners, eventName) => {
17
84
  for (const listener of listeners) {
18
85
  // May already be subscribed
19
86
  _speechRecognitionRef?.removeEventListener(eventName, listener);
@@ -22,22 +89,26 @@ export const ExpoSpeechRecognitionModule = {
22
89
  });
23
90
  // Start the speech recognition!
24
91
  _speechRecognitionRef.start();
25
- },
26
- getStateAsync: () => {
92
+ }
93
+ getStateAsync() {
27
94
  console.warn("getStateAsync is not supported on web. Returning 'inactive'.");
28
95
  return Promise.resolve("inactive");
29
- },
30
- stop: () => _speechRecognitionRef?.stop(),
31
- abort: () => _speechRecognitionRef?.abort(),
32
- requestPermissionsAsync: () => {
96
+ }
97
+ stop() {
98
+ _speechRecognitionRef?.stop();
99
+ }
100
+ abort() {
101
+ _speechRecognitionRef?.abort();
102
+ }
103
+ requestPermissionsAsync() {
33
104
  return Promise.resolve({
34
105
  granted: true,
35
106
  canAskAgain: false,
36
107
  expires: "never",
37
108
  status: "granted",
38
109
  });
39
- },
40
- getPermissionsAsync: () => {
110
+ }
111
+ getPermissionsAsync() {
41
112
  console.warn("getPermissionsAsync is not supported on web. Returning a denied permission response.");
42
113
  return Promise.resolve({
43
114
  granted: false,
@@ -45,66 +116,62 @@ export const ExpoSpeechRecognitionModule = {
45
116
  expires: "never",
46
117
  status: "denied",
47
118
  });
48
- },
49
- getSupportedLocales: async () => {
119
+ }
120
+ async getSupportedLocales() {
50
121
  console.warn("getSupportedLocales is not supported on web. Returning an empty array.");
51
122
  return {
52
123
  locales: [],
53
124
  installedLocales: [],
54
125
  };
55
- },
56
- addListener: () => {
57
- console.warn("addListener is not supported. Use ExpoSpeechRecognitionModuleEmitter(eventName, listener) instead.");
58
- },
59
- removeListeners: () => {
60
- console.warn("removeListeners is not supported. Use ExpoSpeechRecognitionModuleEmitter.removeListener(eventName, listener) instead.");
61
- },
62
- getSpeechRecognitionServices: () => {
126
+ }
127
+ // addListener() {}
128
+ // removeListeners() {}
129
+ getSpeechRecognitionServices() {
63
130
  return [];
64
- },
65
- getDefaultRecognitionService: () => {
131
+ }
132
+ getDefaultRecognitionService() {
66
133
  return {
67
134
  packageName: "",
68
135
  };
69
- },
70
- getAssistantService: () => {
136
+ }
137
+ getAssistantService() {
71
138
  return {
72
139
  packageName: "",
73
140
  };
74
- },
75
- supportsOnDeviceRecognition: () => {
141
+ }
142
+ supportsOnDeviceRecognition() {
76
143
  return false;
77
- },
78
- supportsRecording: () => {
144
+ }
145
+ supportsRecording() {
79
146
  return false;
80
- },
81
- androidTriggerOfflineModelDownload: () => {
147
+ }
148
+ androidTriggerOfflineModelDownload() {
82
149
  console.warn("androidTriggerOfflineModelDownload is not supported on web. Returning false.");
83
150
  return Promise.resolve({
84
151
  status: "opened_dialog",
85
152
  message: "Offline model download is not supported on web.",
86
153
  });
87
- },
88
- setCategoryIOS: () => {
154
+ }
155
+ setCategoryIOS() {
89
156
  console.warn("setCategoryIOS is not supported on web.");
90
- },
91
- getAudioSessionCategoryAndOptionsIOS: () => {
157
+ }
158
+ getAudioSessionCategoryAndOptionsIOS() {
92
159
  console.warn("getAudioSessionCategoryAndOptionsIOS is not supported on web.");
93
160
  return {
94
161
  category: "playAndRecord",
95
162
  categoryOptions: ["defaultToSpeaker", "allowBluetooth"],
96
163
  mode: "measurement",
97
164
  };
98
- },
99
- setAudioSessionActiveIOS: () => {
165
+ }
166
+ setAudioSessionActiveIOS() {
100
167
  console.warn("setAudioSessionActiveIOS is not supported on web.");
101
- },
102
- isRecognitionAvailable: () => {
168
+ }
169
+ isRecognitionAvailable() {
103
170
  const hasSpeechRecognitionAPI = typeof webkitSpeechRecognition !== "undefined" ||
104
171
  typeof SpeechRecognition !== "undefined";
105
172
  return hasSpeechRecognitionAPI;
106
- },
107
- };
173
+ }
174
+ }
108
175
  /**
109
176
  * Convert the web SpeechRecognitionEventMap to the native event map for compatibility
110
177
  */
@@ -135,68 +202,5 @@ const webToNativeEventMap = {
135
202
  start: (ev) => null,
136
203
  soundend: (ev) => null,
137
204
  };
138
- export const ExpoSpeechRecognitionModuleEmitter = {
139
- _nativeListeners: new Map(),
140
- _clientListeners: new Map(),
141
- addListener(eventName, listener) {
142
- // Convert the web event to the native event
143
- const nativeListener = (ev) => {
144
- const eventPayload = webToNativeEventMap[eventName]?.(ev);
145
- listener(eventPayload);
146
- };
147
- _speechRecognitionRef?.addEventListener(eventName, nativeListener);
148
- if (!ExpoSpeechRecognitionModuleEmitter._nativeListeners.has(eventName)) {
149
- ExpoSpeechRecognitionModuleEmitter._nativeListeners.set(eventName, new Set());
150
- }
151
- // Add the original listener to the enhanced listeners
152
- ExpoSpeechRecognitionModuleEmitter._nativeListeners
153
- .get(eventName)
154
- ?.add(nativeListener);
155
- // Map the original listener to the enhanced listener
156
- ExpoSpeechRecognitionModuleEmitter._clientListeners.set(listener, nativeListener);
157
- return {
158
- remove: () => {
159
- _speechRecognitionRef?.removeEventListener(eventName, nativeListener);
160
- ExpoSpeechRecognitionModuleEmitter._nativeListeners
161
- .get(eventName)
162
- ?.delete(nativeListener);
163
- ExpoSpeechRecognitionModuleEmitter._clientListeners.delete(listener);
164
- },
165
- };
166
- },
167
- removeListener: (eventName, listener) => {
168
- const resolvedListener = ExpoSpeechRecognitionModuleEmitter._clientListeners.get(listener) ??
169
- listener;
170
- _speechRecognitionRef?.removeEventListener(eventName, resolvedListener);
171
- if (ExpoSpeechRecognitionModuleEmitter._nativeListeners.has(eventName)) {
172
- ExpoSpeechRecognitionModuleEmitter._nativeListeners
173
- .get(eventName)
174
- ?.delete(listener);
175
- }
176
- ExpoSpeechRecognitionModuleEmitter._clientListeners.delete(listener);
177
- },
178
- removeAllListeners: (eventName) => {
179
- // Go through _listeners and remove all listeners for this event
180
- if (ExpoSpeechRecognitionModuleEmitter._nativeListeners.has(eventName)) {
181
- const nativeListeners = ExpoSpeechRecognitionModuleEmitter._nativeListeners.get(eventName);
182
- if (!nativeListeners) {
183
- return;
184
- }
185
- // Remove the enhanced listeners
186
- for (const [listener, nativeListener,] of ExpoSpeechRecognitionModuleEmitter._clientListeners) {
187
- // if nativeListener in listeners, remove it
188
- if (nativeListeners.has(nativeListener)) {
189
- // Remove the enhanced listener
190
- ExpoSpeechRecognitionModuleEmitter._clientListeners.delete(listener);
191
- }
192
- }
193
- // Remove the native listeners
194
- for (const listener of nativeListeners) {
195
- ExpoSpeechRecognitionModuleEmitter.removeListener(eventName, listener);
196
- }
197
- // Clean up
198
- ExpoSpeechRecognitionModuleEmitter._nativeListeners.delete(eventName);
199
- }
200
- },
201
- };
205
+ export const ExpoSpeechRecognitionModule = registerWebModule(ExpoSpeechRecognitionModuleWeb);
202
206
  //# sourceMappingURL=ExpoSpeechRecognitionModule.web.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ExpoSpeechRecognitionModule.web.js","sourceRoot":"","sources":["../src/ExpoSpeechRecognitionModule.web.ts"],"names":[],"mappings":"AAMA,IAAI,qBAAqB,GAA6B,IAAI,CAAC;AAE3D,kEAAkE;AAClE,4EAA4E;AAC5E,MAAM,CAAC,MAAM,2BAA2B,GAAoC;IAC1E,KAAK,EAAE,CAAC,OAAO,EAAE,EAAE;QACjB,MAAM,sBAAsB,GAC1B,OAAO,uBAAuB,KAAK,WAAW;YAC5C,CAAC,CAAC,uBAAuB;YACzB,CAAC,CAAC,iBAAiB,CAAC;QACxB,qBAAqB,GAAG,IAAI,sBAAsB,EAAE,CAAC;QACrD,qBAAqB,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,OAAO,CAAC;QACrD,qBAAqB,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,KAAK,CAAC;QACvE,qBAAqB,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,CAAC;QACrE,qBAAqB,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,KAAK,CAAC;QAE/D,oDAAoD;QACpD,oGAAoG;QACpG,kCAAkC,CAAC,gBAAgB,CAAC,OAAO,CACzD,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE;YACvB,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;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YACzE,CAAC;YAED,WAAW;YACX,kCAAkC,CAAC,gBAAgB,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACxE,CAAC;IACH,CAAC;CACF,CAAC","sourcesContent":["import type { PermissionResponse } from \"expo-modules-core\";\nimport type {\n ExpoSpeechRecognitionModuleType,\n ExpoSpeechRecognitionNativeEventMap,\n} from \"./ExpoSpeechRecognitionModule.types\";\n\nlet _speechRecognitionRef: SpeechRecognition | null = null;\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.\nexport const ExpoSpeechRecognitionModule: ExpoSpeechRecognitionModuleType = {\n start: (options) => {\n const SpeechRecognitionClass =\n typeof webkitSpeechRecognition !== \"undefined\"\n ? webkitSpeechRecognition\n : SpeechRecognition;\n _speechRecognitionRef = new SpeechRecognitionClass();\n _speechRecognitionRef.lang = options.lang ?? \"en-US\";\n _speechRecognitionRef.interimResults = options.interimResults ?? false;\n _speechRecognitionRef.maxAlternatives = options.maxAlternatives ?? 1;\n _speechRecognitionRef.continuous = options.continuous ?? false;\n\n // Re-subscribe to events so that we don't lose them\n // This covers the case where the user has already subscribed to an event prior to calling `start()`\n ExpoSpeechRecognitionModuleEmitter._nativeListeners.forEach(\n (listeners, eventName) => {\n for (const listener of listeners) {\n // May already be subscribed\n _speechRecognitionRef?.removeEventListener(eventName, listener);\n _speechRecognitionRef?.addEventListener(eventName, listener);\n }\n },\n );\n\n // Start the speech recognition!\n _speechRecognitionRef.start();\n },\n getStateAsync: () => {\n console.warn(\n \"getStateAsync is not supported on web. Returning 'inactive'.\",\n );\n return Promise.resolve(\"inactive\");\n },\n stop: () => _speechRecognitionRef?.stop(),\n abort: () => _speechRecognitionRef?.abort(),\n requestPermissionsAsync: () => {\n return Promise.resolve({\n granted: true,\n canAskAgain: false,\n expires: \"never\",\n status: \"granted\",\n } as PermissionResponse);\n },\n getPermissionsAsync: () => {\n console.warn(\n \"getPermissionsAsync is not supported on web. Returning a denied permission response.\",\n );\n return Promise.resolve({\n granted: false,\n canAskAgain: false,\n expires: \"never\",\n status: \"denied\",\n } as PermissionResponse);\n },\n getSupportedLocales: async () => {\n console.warn(\n \"getSupportedLocales is not supported on web. Returning an empty array.\",\n );\n return {\n locales: [] as string[],\n installedLocales: [] as string[],\n };\n },\n addListener: () => {\n console.warn(\n \"addListener is not supported. Use ExpoSpeechRecognitionModuleEmitter(eventName, listener) instead.\",\n );\n },\n removeListeners: () => {\n console.warn(\n \"removeListeners is not supported. Use ExpoSpeechRecognitionModuleEmitter.removeListener(eventName, listener) instead.\",\n );\n },\n getSpeechRecognitionServices: () => {\n return [] as string[];\n },\n getDefaultRecognitionService: () => {\n return {\n packageName: \"\",\n };\n },\n getAssistantService: () => {\n return {\n packageName: \"\",\n };\n },\n supportsOnDeviceRecognition: () => {\n return false;\n },\n supportsRecording: () => {\n return false;\n },\n androidTriggerOfflineModelDownload: () => {\n console.warn(\n \"androidTriggerOfflineModelDownload is not supported on web. Returning false.\",\n );\n return Promise.resolve({\n status: \"opened_dialog\",\n message: \"Offline model download is not supported on web.\",\n });\n },\n setCategoryIOS: () => {\n console.warn(\"setCategoryIOS is not supported on web.\");\n },\n getAudioSessionCategoryAndOptionsIOS: () => {\n console.warn(\n \"getAudioSessionCategoryAndOptionsIOS is not supported on web.\",\n );\n return {\n category: \"playAndRecord\",\n categoryOptions: [\"defaultToSpeaker\", \"allowBluetooth\"],\n mode: \"measurement\",\n };\n },\n setAudioSessionActiveIOS: () => {\n console.warn(\"setAudioSessionActiveIOS is not supported on web.\");\n },\n isRecognitionAvailable: () => {\n const hasSpeechRecognitionAPI =\n typeof webkitSpeechRecognition !== \"undefined\" ||\n typeof SpeechRecognition !== \"undefined\";\n\n return hasSpeechRecognitionAPI;\n },\n};\n\n/**\n * Convert the web SpeechRecognitionEventMap to the native event map for compatibility\n */\nconst webToNativeEventMap: {\n [K in keyof SpeechRecognitionEventMap]: (\n ev: SpeechRecognitionEventMap[K],\n ) => ExpoSpeechRecognitionNativeEventMap[K];\n} = {\n audioend: (ev) => ({ uri: null }),\n audiostart: (ev) => ({ uri: null }),\n end: (ev) => null,\n error: (ev) => ({ error: ev.error, message: ev.message }),\n nomatch: (ev) => null,\n result: (ev) => {\n const nativeResults: ExpoSpeechRecognitionNativeEventMap[\"result\"][\"results\"] =\n [];\n\n for (let i = 0; i < ev.results[ev.resultIndex].length; i++) {\n const result = ev.results[ev.resultIndex][i];\n nativeResults.push({\n transcript: result.transcript,\n confidence: result.confidence,\n segments: [],\n });\n }\n\n return {\n isFinal: Boolean(ev.results[ev.resultIndex]?.isFinal),\n results: nativeResults,\n };\n },\n soundstart: (ev) => null,\n speechend: (ev) => null,\n speechstart: (ev) => null,\n start: (ev) => null,\n soundend: (ev) => null,\n};\n\nexport const ExpoSpeechRecognitionModuleEmitter = {\n _nativeListeners: new Map() as Map<string, Set<(event: any) => void>>,\n _clientListeners: new Map() as Map<\n // Original listener\n (event: any) => void,\n // Native listener\n (event: any) => void\n >,\n addListener<T extends keyof SpeechRecognitionEventMap>(\n eventName: T,\n listener: (ev: ExpoSpeechRecognitionNativeEventMap[T]) => void,\n ) {\n // Convert the web event to the native event\n const nativeListener = (ev: SpeechRecognitionEventMap[T]) => {\n const eventPayload = webToNativeEventMap[eventName]?.(ev);\n listener(eventPayload);\n };\n\n _speechRecognitionRef?.addEventListener(eventName, nativeListener);\n if (!ExpoSpeechRecognitionModuleEmitter._nativeListeners.has(eventName)) {\n ExpoSpeechRecognitionModuleEmitter._nativeListeners.set(\n eventName,\n new Set(),\n );\n }\n // Add the original listener to the enhanced listeners\n ExpoSpeechRecognitionModuleEmitter._nativeListeners\n .get(eventName)\n ?.add(nativeListener);\n\n // Map the original listener to the enhanced listener\n ExpoSpeechRecognitionModuleEmitter._clientListeners.set(\n listener,\n nativeListener,\n );\n\n return {\n remove: () => {\n _speechRecognitionRef?.removeEventListener(eventName, nativeListener);\n ExpoSpeechRecognitionModuleEmitter._nativeListeners\n .get(eventName)\n ?.delete(nativeListener);\n ExpoSpeechRecognitionModuleEmitter._clientListeners.delete(listener);\n },\n };\n },\n removeListener: (eventName: string, listener: (event: any) => void) => {\n const resolvedListener =\n ExpoSpeechRecognitionModuleEmitter._clientListeners.get(listener) ??\n listener;\n\n _speechRecognitionRef?.removeEventListener(eventName, resolvedListener);\n if (ExpoSpeechRecognitionModuleEmitter._nativeListeners.has(eventName)) {\n ExpoSpeechRecognitionModuleEmitter._nativeListeners\n .get(eventName)\n ?.delete(listener);\n }\n ExpoSpeechRecognitionModuleEmitter._clientListeners.delete(listener);\n },\n removeAllListeners: (eventName: string) => {\n // Go through _listeners and remove all listeners for this event\n if (ExpoSpeechRecognitionModuleEmitter._nativeListeners.has(eventName)) {\n const nativeListeners =\n ExpoSpeechRecognitionModuleEmitter._nativeListeners.get(eventName);\n if (!nativeListeners) {\n return;\n }\n\n // Remove the enhanced listeners\n for (const [\n listener,\n nativeListener,\n ] of ExpoSpeechRecognitionModuleEmitter._clientListeners) {\n // if nativeListener in listeners, remove it\n if (nativeListeners.has(nativeListener)) {\n // Remove the enhanced listener\n ExpoSpeechRecognitionModuleEmitter._clientListeners.delete(listener);\n }\n }\n\n // Remove the native listeners\n for (const listener of nativeListeners) {\n ExpoSpeechRecognitionModuleEmitter.removeListener(eventName, listener);\n }\n\n // Clean up\n ExpoSpeechRecognitionModuleEmitter._nativeListeners.delete(eventName);\n }\n },\n};\n"]}
1
+ {"version":3,"file":"ExpoSpeechRecognitionModule.web.js","sourceRoot":"","sources":["../src/ExpoSpeechRecognitionModule.web.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,MAAM,CAAC;AAOvD,IAAI,qBAAqB,GAA6B,IAAI,CAAC;AAM3D,kEAAkE;AAClE,4EAA4E;AAC5E,MAAM,8BAA+B,SAAQ,YAA+C;IAC1F,gBAAgB,GAKZ,IAAI,GAAG,EAAE,CAAC;IAEd,gBAAgB,GAA0C,IAAI,GAAG,EAAE,CAAC;IAE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I;IACvB,WAAW,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI;IACzB,KAAK,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI;IACnB,QAAQ,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI;CACvB,CAAC;AAEF,MAAM,CAAC,MAAM,2BAA2B,GAAG,iBAAiB,CAC1D,8BAA8B,CAC/B,CAAC","sourcesContent":["import type { EventSubscription, PermissionResponse } from \"expo-modules-core\";\nimport { registerWebModule, NativeModule } from \"expo\";\nimport type {\n ExpoSpeechRecognitionNativeEventMap,\n ExpoSpeechRecognitionNativeEvents,\n ExpoSpeechRecognitionOptions,\n} from \"./ExpoSpeechRecognitionModule.types\";\n\nlet _speechRecognitionRef: SpeechRecognition | null = null;\n\ntype NativeEventListener = (\n event: SpeechRecognitionEventMap[keyof SpeechRecognitionEventMap],\n) => void;\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.\nclass ExpoSpeechRecognitionModuleWeb extends NativeModule<ExpoSpeechRecognitionNativeEvents> {\n _clientListeners: Map<\n // Original listener\n ExpoSpeechRecognitionNativeEvents[keyof ExpoSpeechRecognitionNativeEvents],\n // Native listener\n NativeEventListener\n > = new Map();\n\n _nativeListeners: Map<string, Set<NativeEventListener>> = new Map();\n\n // Convert the web event to the native event\n bindEventListener = <T extends keyof SpeechRecognitionEventMap>(\n eventName: T,\n ev: SpeechRecognitionEventMap[T],\n ) => {\n const eventPayload = webToNativeEventMap[eventName]?.(ev);\n\n this.emit(\n eventName,\n // @ts-expect-error payload typings are incorrect\n eventPayload,\n );\n };\n\n addListener<EventName extends keyof ExpoSpeechRecognitionNativeEventMap>(\n eventName: EventName,\n listener: ExpoSpeechRecognitionNativeEvents[EventName],\n ): EventSubscription {\n // Convert the web event to the native event\n\n // @ts-expect-error Not all events are covered here\n const nativeListener = (ev: SpeechRecognitionEventMap[EventName]) => {\n const handler =\n eventName in webToNativeEventMap\n ? webToNativeEventMap[eventName as keyof SpeechRecognitionEventMap]\n : null;\n\n // @ts-expect-error payload typings are incorrect\n const eventPayload = handler?.(ev);\n\n // @ts-expect-error\n listener(eventPayload);\n };\n\n // @ts-expect-error\n _speechRecognitionRef?.addEventListener(eventName, nativeListener);\n if (!this._nativeListeners.has(eventName)) {\n this._nativeListeners.set(eventName, new Set());\n }\n // Add the original listener to the enhanced listeners\n // @ts-expect-error\n this._nativeListeners.get(eventName)?.add(nativeListener);\n // Map the original listener to the enhanced listener\n // @ts-expect-error\n this._clientListeners.set(listener, nativeListener);\n\n const handle = super.addListener(eventName, listener);\n\n return {\n remove: () => {\n // @ts-expect-error\n this._nativeListeners.get(eventName)?.delete(nativeListener);\n this._clientListeners.delete(listener);\n handle.remove();\n },\n };\n }\n\n removeAllListeners(\n eventName: keyof ExpoSpeechRecognitionNativeEventMap,\n ): void {\n // Go through _listeners and remove all listeners for this event\n if (this._nativeListeners.has(eventName)) {\n const nativeListeners = this._nativeListeners.get(eventName);\n if (!nativeListeners) {\n return;\n }\n\n // Remove the enhanced listeners\n for (const [listener, nativeListener] of this._clientListeners) {\n // if nativeListener in listeners, remove it\n if (nativeListeners.has(nativeListener)) {\n // Remove the enhanced listener\n this.removeListener(eventName, listener);\n }\n }\n\n // ...and the native listeners\n for (const listener of nativeListeners) {\n // @ts-expect-error\n this.removeListener(eventName, listener);\n }\n\n // Clean up\n this._nativeListeners.delete(eventName);\n }\n }\n\n start(options: ExpoSpeechRecognitionOptions) {\n const SpeechRecognitionClass =\n typeof webkitSpeechRecognition !== \"undefined\"\n ? webkitSpeechRecognition\n : SpeechRecognition;\n _speechRecognitionRef = new SpeechRecognitionClass();\n _speechRecognitionRef.lang = options.lang ?? \"en-US\";\n _speechRecognitionRef.interimResults = options.interimResults ?? false;\n _speechRecognitionRef.maxAlternatives = options.maxAlternatives ?? 1;\n _speechRecognitionRef.continuous = options.continuous ?? false;\n\n // Re-subscribe to events so that we don't lose them\n // This covers the case where the user has already subscribed to an event prior to calling `start()`\n this._nativeListeners.forEach((listeners, eventName) => {\n for (const listener of listeners) {\n // May already be subscribed\n _speechRecognitionRef?.removeEventListener(eventName, listener);\n _speechRecognitionRef?.addEventListener(eventName, listener);\n }\n });\n\n // Start the speech recognition!\n _speechRecognitionRef.start();\n }\n\n getStateAsync() {\n console.warn(\n \"getStateAsync is not supported on web. Returning 'inactive'.\",\n );\n return Promise.resolve(\"inactive\");\n }\n\n stop() {\n _speechRecognitionRef?.stop();\n }\n abort() {\n _speechRecognitionRef?.abort();\n }\n\n requestPermissionsAsync() {\n return Promise.resolve({\n granted: true,\n canAskAgain: false,\n expires: \"never\",\n status: \"granted\",\n } as PermissionResponse);\n }\n\n getPermissionsAsync() {\n console.warn(\n \"getPermissionsAsync is not supported on web. Returning a denied permission response.\",\n );\n return Promise.resolve({\n granted: false,\n canAskAgain: false,\n expires: \"never\",\n status: \"denied\",\n } as PermissionResponse);\n }\n\n async getSupportedLocales() {\n console.warn(\n \"getSupportedLocales is not supported on web. Returning an empty array.\",\n );\n return {\n locales: [] as string[],\n installedLocales: [] as string[],\n };\n }\n\n // addListener() {}\n\n // removeListeners() {}\n\n getSpeechRecognitionServices() {\n return [] as string[];\n }\n\n getDefaultRecognitionService() {\n return {\n packageName: \"\",\n };\n }\n\n getAssistantService() {\n return {\n packageName: \"\",\n };\n }\n\n supportsOnDeviceRecognition() {\n return false;\n }\n\n supportsRecording() {\n return false;\n }\n\n androidTriggerOfflineModelDownload() {\n console.warn(\n \"androidTriggerOfflineModelDownload is not supported on web. Returning false.\",\n );\n return Promise.resolve({\n status: \"opened_dialog\",\n message: \"Offline model download is not supported on web.\",\n });\n }\n\n setCategoryIOS() {\n console.warn(\"setCategoryIOS is not supported on web.\");\n }\n\n getAudioSessionCategoryAndOptionsIOS() {\n console.warn(\n \"getAudioSessionCategoryAndOptionsIOS is not supported on web.\",\n );\n return {\n category: \"playAndRecord\",\n categoryOptions: [\"defaultToSpeaker\", \"allowBluetooth\"],\n mode: \"measurement\",\n };\n }\n\n setAudioSessionActiveIOS() {\n console.warn(\"setAudioSessionActiveIOS is not supported on web.\");\n }\n\n isRecognitionAvailable() {\n const hasSpeechRecognitionAPI =\n typeof webkitSpeechRecognition !== \"undefined\" ||\n typeof SpeechRecognition !== \"undefined\";\n\n return hasSpeechRecognitionAPI;\n }\n}\n\n/**\n * Convert the web SpeechRecognitionEventMap to the native event map for compatibility\n */\nconst webToNativeEventMap: {\n [K in keyof SpeechRecognitionEventMap]: (\n ev: SpeechRecognitionEventMap[K],\n ) => ExpoSpeechRecognitionNativeEventMap[K];\n} = {\n audioend: (ev) => ({ uri: null }),\n audiostart: (ev) => ({ uri: null }),\n end: (ev) => null,\n error: (ev) => ({ error: ev.error, message: ev.message }),\n nomatch: (ev) => null,\n result: (ev) => {\n const nativeResults: ExpoSpeechRecognitionNativeEventMap[\"result\"][\"results\"] =\n [];\n\n for (let i = 0; i < ev.results[ev.resultIndex].length; i++) {\n const result = ev.results[ev.resultIndex][i];\n nativeResults.push({\n transcript: result.transcript,\n confidence: result.confidence,\n segments: [],\n });\n }\n\n return {\n isFinal: Boolean(ev.results[ev.resultIndex]?.isFinal),\n results: nativeResults,\n };\n },\n soundstart: (ev) => null,\n speechend: (ev) => null,\n speechstart: (ev) => null,\n start: (ev) => null,\n soundend: (ev) => null,\n};\n\nexport const ExpoSpeechRecognitionModule = registerWebModule(\n ExpoSpeechRecognitionModuleWeb,\n);\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ExpoWebSpeechRecognition.d.ts","sourceRoot":"","sources":["../src/ExpoWebSpeechRecognition.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAEV,4BAA4B,EAC7B,MAAM,qCAAqC,CAAC;AAiJ7C,KAAK,cAAc,CAAC,CAAC,SAAS,MAAM,yBAAyB,IAAI,CAC/D,IAAI,EAAE,iBAAiB,EACvB,EAAE,EAAE,yBAAyB,CAAC,CAAC,CAAC,KAC7B,GAAG,CAAC;AAET,8FAA8F;AAC9F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MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;IAI1D,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,oBAAoB;IAIzC,aAAa,YAAa,MAAM,WAAW,MAAM,UAK/C;CACH;AAED,qBAAa,oBAAqB,YAAW,aAAa;IACxD,GAAG,SAAM;IACT,MAAM,SAAK;gBAEC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM;CAIzC"}
@@ -1,6 +1,4 @@
1
- // Import the native module. On web, it will be resolved to ExpoSpeechRecognition.web.ts
2
- // and on native platforms to ExpoSpeechRecognition.ts
3
- import { ExpoSpeechRecognitionModule, ExpoSpeechRecognitionModuleEmitter, } from "./ExpoSpeechRecognitionModule";
1
+ import { ExpoSpeechRecognitionModule } from "./ExpoSpeechRecognitionModule";
4
2
  const noop = () => { };
5
3
  const createEventData = (target) => ({
6
4
  AT_TARGET: 2,
@@ -290,7 +288,9 @@ export class ExpoWebSpeechRecognition {
290
288
  // Enhance the native listener with any necessary polyfills
291
289
  const enhancedEvent = WebListenerTransformers[type]?.(this, wrappedListener) ??
292
290
  stubEvent(type, this, wrappedListener);
293
- const subscription = ExpoSpeechRecognitionModuleEmitter.addListener(enhancedEvent.eventName, enhancedEvent.nativeListener);
291
+ const subscription = ExpoSpeechRecognitionModule.addListener(enhancedEvent.eventName,
292
+ // @ts-expect-error
293
+ enhancedEvent.nativeListener);
294
294
  // Store the subscriptions so we can remove them later
295
295
  // This is keyed by the listener function so we can remove all subscriptions for a given listener
296
296
  this.#subscriptionMap.set(listener, [subscription]);