expo-speech-recognition 0.0.1 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.eslintrc.js +12 -0
  2. package/.prettierignore +6 -0
  3. package/README.md +893 -0
  4. package/android/build.gradle +43 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/expo/modules/speechrecognition/DelayedFileStreamer.kt +232 -0
  7. package/android/src/main/java/expo/modules/speechrecognition/ExpoAudioRecorder.kt +217 -0
  8. package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionModule.kt +424 -0
  9. package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionOptions.kt +97 -0
  10. package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechService.kt +669 -0
  11. package/app.plugin.js +105 -0
  12. package/build/ExpoSpeechRecognitionModule.d.ts +5 -0
  13. package/build/ExpoSpeechRecognitionModule.d.ts.map +1 -0
  14. package/build/ExpoSpeechRecognitionModule.js +6 -0
  15. package/build/ExpoSpeechRecognitionModule.js.map +1 -0
  16. package/build/ExpoSpeechRecognitionModule.types.d.ts +579 -0
  17. package/build/ExpoSpeechRecognitionModule.types.d.ts.map +1 -0
  18. package/build/ExpoSpeechRecognitionModule.types.js +2 -0
  19. package/build/ExpoSpeechRecognitionModule.types.js.map +1 -0
  20. package/build/ExpoSpeechRecognitionModule.web.d.ts +12 -0
  21. package/build/ExpoSpeechRecognitionModule.web.d.ts.map +1 -0
  22. package/build/ExpoSpeechRecognitionModule.web.js +201 -0
  23. package/build/ExpoSpeechRecognitionModule.web.js.map +1 -0
  24. package/build/ExpoWebSpeechRecognition.d.ts +98 -0
  25. package/build/ExpoWebSpeechRecognition.d.ts.map +1 -0
  26. package/build/ExpoWebSpeechRecognition.js +387 -0
  27. package/build/ExpoWebSpeechRecognition.js.map +1 -0
  28. package/build/ExpoWebSpeechRecognition.web.d.ts +13 -0
  29. package/build/ExpoWebSpeechRecognition.web.d.ts.map +1 -0
  30. package/build/ExpoWebSpeechRecognition.web.js +17 -0
  31. package/build/ExpoWebSpeechRecognition.web.js.map +1 -0
  32. package/build/constants.d.ts +344 -0
  33. package/build/constants.d.ts.map +1 -0
  34. package/build/constants.js +344 -0
  35. package/build/constants.js.map +1 -0
  36. package/build/index.d.ts +26 -0
  37. package/build/index.d.ts.map +1 -0
  38. package/build/index.js +18 -0
  39. package/build/index.js.map +1 -0
  40. package/build/useSpeechRecognitionEvent.d.ts +11 -0
  41. package/build/useSpeechRecognitionEvent.d.ts.map +1 -0
  42. package/build/useSpeechRecognitionEvent.js +20 -0
  43. package/build/useSpeechRecognitionEvent.js.map +1 -0
  44. package/expo-module.config.json +9 -0
  45. package/ios/EXSpeechRecognitionPermissionRequester.swift +42 -0
  46. package/ios/ExpoSpeechRecognition.podspec +27 -0
  47. package/ios/ExpoSpeechRecognitionException.swift +84 -0
  48. package/ios/ExpoSpeechRecognitionModule.swift +480 -0
  49. package/ios/ExpoSpeechRecognizer.swift +712 -0
  50. package/ios/SpeechRecognitionOptions.swift +183 -0
  51. package/package.json +43 -6
  52. package/src/ExpoSpeechRecognitionModule.ts +16 -0
  53. package/src/ExpoSpeechRecognitionModule.types.ts +622 -0
  54. package/src/ExpoSpeechRecognitionModule.web.ts +268 -0
  55. package/src/ExpoWebSpeechRecognition.ts +512 -0
  56. package/src/ExpoWebSpeechRecognition.web.ts +17 -0
  57. package/src/constants.ts +349 -0
  58. package/src/globals.d.ts +1 -0
  59. package/src/index.ts +74 -0
  60. package/src/useSpeechRecognitionEvent.ts +30 -0
  61. package/tsconfig.json +8 -0
  62. package/index.js +0 -0
package/README.md ADDED
@@ -0,0 +1,893 @@
1
+ # 🎙️ expo-speech-recognition
2
+
3
+ ![NPM Version](https://img.shields.io/npm/v/%40jamsch%2Fexpo-speech-recognition)
4
+
5
+ expo-speech-recognition implements the iOS [`SFSpeechRecognizer`](https://developer.apple.com/documentation/speech/sfspeechrecognizer), Android [`SpeechRecognizer`](https://developer.android.com/reference/android/speech/SpeechRecognizer) and Web [`SpeechRecognition`](https://wicg.github.io/speech-api/) for React Native projects with the goal of code reuse across web and mobile.
6
+
7
+ ![expo-speech-recognition preview](./images/preview.gif)
8
+
9
+ ## Table of Contents
10
+
11
+ - [Installation](#installation)
12
+ - [Usage](#usage)
13
+ - [Using Hooks](#using-hooks)
14
+ - [Permissions](#permissions)
15
+ - [Direct module API](#direct-module-api)
16
+ - [Speech Recognition Events](#speech-recognition-events)
17
+ - [Handling Errors](#handling-errors)
18
+ - [Persisting Audio Recordings](#persisting-audio-recordings)
19
+ - [Transcribing audio files](#transcribing-audio-files)
20
+ - [Supported input audio formats](#supported-input-audio-formats)
21
+ - [Android](#android)
22
+ - [iOS](#ios)
23
+ - [File transcription example](#file-transcription-example)
24
+ - [Polyfilling the Web SpeechRecognition API](#polyfilling-the-web-speechrecognition-api)
25
+ - [Muting the beep sound on Android](#muting-the-beep-sound-on-android)
26
+ - [Improving accuracy of single-word prompts](#improving-accuracy-of-single-word-prompts)
27
+ - [Platform Compatibility Table](#platform-compatibility-table)
28
+ - [API Methods](#api-methods)
29
+ - [start()](#startoptions-speechrecognitionoptions-void)
30
+ - [stop()](#stop-void)
31
+ - [abort()](#abort-void)
32
+ - [requestPermissionsAsync()](#requestpermissionsasync-promisepermissionresponse)
33
+ - [getPermissionsAsync()](#getpermissionsasync-promisepermissionresponse)
34
+ - [getStateAsync()](#getstateasync-promisespeechrecognitionstate)
35
+ - [addSpeechRecognitionListener()](#addspeechrecognitionlistenereventname-string-listener-event-any--void--remove---void-)
36
+ - [getSupportedLocales()](#getsupportedlocales-promise-locales-string-installedlocales-string-)
37
+ - [getSpeechRecognitionServices()](#getspeechrecognitionservices-string-android-only)
38
+ - [getDefaultRecognitionService()](#getdefaultrecognitionservice--packagename-string--android-only)
39
+ - [getAssistantService()](#getassistantservice--packagename-string--android-only)
40
+ - [supportsOnDeviceRecognition()](#supportsondevicerecognition-boolean-android-only)
41
+ - [supportsRecording()](#supportsrecording-boolean-android-only)
42
+ - [androidTriggerOfflineModelDownload()](#androidtriggerofflinemodeldownload-locale-string--promise-status-opened_dialog--download_success--download_canceled-message-string-)
43
+ - [setCategoryIOS()](#setcategoryios-void-ios-only)
44
+ - [getAudioSessionCategoryAndOptionsIOS()](#getaudiosessioncategoryandoptionsios-ios-only)
45
+ - [setAudioSessionActiveIOS()](#setaudiosessionactiveiosvalue-boolean-options--notifyothersondeactivation-boolean--void)
46
+
47
+ ## Installation
48
+
49
+ 1. Install the package
50
+
51
+ ```
52
+ npm install expo-speech-recognition
53
+ ```
54
+
55
+ 2. Configure the config plugin.
56
+
57
+ > The config plugin updates the Android App Manifest to include package visibility filtering for `com.google.android.googlequicksearchbox` (Google's Speech Recognition) along with the required permissions for Android and iOS.
58
+
59
+ ```js
60
+ // app.json
61
+ {
62
+ "expo": {
63
+ "plugins": [
64
+ [
65
+ "expo-speech-recognition",
66
+ {
67
+ "microphonePermission": "Allow $(PRODUCT_NAME) to use the microphone.",
68
+ "speechRecognitionPermission": "Allow $(PRODUCT_NAME) to use speech recognition.",
69
+ // Add additional speech service packages here that aren't listed
70
+ // under the `forceQueryable` section when running the command:
71
+ // "adb shell dumpsys package queries"
72
+ // default: ["com.google.android.googlequicksearchbox"]
73
+ "androidSpeechServicePackages": ["com.google.android.googlequicksearchbox"]
74
+ }
75
+ ]
76
+ ]
77
+ }
78
+ }
79
+ ```
80
+
81
+ ## Usage
82
+
83
+ ### Using Hooks
84
+
85
+ Using hooks is the easiest way to get started. The `useSpeechRecognitionEvent` hook allows you to register native event listeners.
86
+
87
+ ```tsx
88
+ import {
89
+ ExpoSpeechRecognitionModule,
90
+ useSpeechRecognitionEvent,
91
+ } from "expo-speech-recognition";
92
+
93
+ function App() {
94
+ const [recognizing, setRecognizing] = useState(false);
95
+ const [transcript, setTranscript] = useState("");
96
+
97
+ useSpeechRecognitionEvent("start", () => setRecognizing(true));
98
+ useSpeechRecognitionEvent("end", () => setRecognizing(false));
99
+ useSpeechRecognitionEvent("result", (event) => {
100
+ setTranscript(event.results[0].transcript);
101
+ });
102
+ useSpeechRecognitionEvent("error", (event) => {
103
+ console.log("error code:", event.error, "error messsage:", event.message);
104
+ });
105
+
106
+ const handleStart = () => {
107
+ ExpoSpeechRecognitionModule.requestPermissionsAsync().then((result) => {
108
+ if (!result.granted) {
109
+ console.warn("Permissions not granted", result);
110
+ return;
111
+ }
112
+ // Start speech recognition
113
+ ExpoSpeechRecognitionModule.start({
114
+ lang: "en-US",
115
+ interimResults: true,
116
+ maxAlternatives: 1,
117
+ continuous: false,
118
+ requiresOnDeviceRecognition: false,
119
+ addsPunctuation: false,
120
+ contextualStrings: ["Carlsen", "Nepomniachtchi", "Praggnanandhaa"],
121
+ });
122
+ });
123
+ };
124
+
125
+ return (
126
+ <View>
127
+ {recognizing ? (
128
+ <Button title="Start" onPress={handleStart} />
129
+ ) : (
130
+ <Button title="Stop" onPress={ExpoSpeechRecognitionModule.stop} />
131
+ )}
132
+
133
+ <ScrollView>
134
+ <Text>{transcript}</Text>
135
+ </ScrollView>
136
+ </View>
137
+ );
138
+ }
139
+ ```
140
+
141
+ ### Permissions
142
+
143
+ You should request permissions prior to starting recognition. This library exports two functions: `getPermissionsAsync` and `requestPermissionsAsync` for this purpose. If you do not request permissions or the user has denied permissions after starting, expect an `error` event with the `error` code set to `not-allowed`.
144
+
145
+ ```ts
146
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
147
+
148
+ ExpoSpeechRecognitionModule.getPermissionsAsync().then((result) => {
149
+ console.log("Status:", result.status);
150
+ console.log("Granted:", result.granted);
151
+ console.log("Can ask again:", result.canAskAgain);
152
+ console.log("Expires:", result.expires);
153
+ });
154
+
155
+ ExpoSpeechRecognitionModule.requestPermissionsAsync().then((result) => {
156
+ if (!result.granted) {
157
+ console.warn("Permissions not granted", result);
158
+ return;
159
+ }
160
+ // Permissions granted! Start speech recognition, or at some other time...
161
+ ExpoSpeechRecognitionModule.start({ lang: "en-US" });
162
+ });
163
+ ```
164
+
165
+ ### Direct module API
166
+
167
+ You can also use the `ExpoSpeechRecognitionModule` to use the native APIs directly. The listener events are similar to the Web Speech API.
168
+
169
+ ```ts
170
+ import {
171
+ ExpoSpeechRecognitionModule,
172
+ addSpeechRecognitionListener,
173
+ } from "expo-speech-recognition";
174
+
175
+ // Register event listeners
176
+ const startListener = addSpeechRecognitionListener("start", () => {
177
+ console.log("Speech recognition started");
178
+ });
179
+
180
+ // and remove the listener when you're done:
181
+ startListener.remove();
182
+
183
+ const endListener = addSpeechRecognitionListener("end", () => {
184
+ console.log("Speech recognition ended");
185
+ });
186
+
187
+ const resultListener = addSpeechRecognitionListener("result", (event) => {
188
+ // Note: this is not the same as the `result` event listener on the web speech API
189
+ // event.results is an array of results (e.g. `[{ transcript: "hello", confidence: 0.5, segments: [] }]`)
190
+ console.log("results:", event.results, "final:", event.isFinal);
191
+ });
192
+
193
+ const errorListener = addSpeechRecognitionListener("error", (event) => {
194
+ console.log("error code:", event.error, "error messsage:", event.message);
195
+ });
196
+
197
+ // Start speech recognition
198
+ ExpoSpeechRecognitionModule.start({
199
+ lang: "en-US",
200
+ // Whether to return results as they become available without waiting for the final result.
201
+ interimResults: true,
202
+ // The maximum number of alternative transcriptions to return.
203
+ maxAlternatives: 1,
204
+ // Continuous recognition. Note: if false on iOS, recognition will run until no speech is detected for 3 seconds
205
+ continuous: true,
206
+ // [Default: false] Prevent device from sending audio over the network. Only enabled if the device supports it.
207
+ requiresOnDeviceRecognition: false,
208
+ // [Default: false] Include punctuation in the recognition results. This applies to full stops and commas.
209
+ addsPunctuation: false,
210
+ // [Default: undefined] Short custom phrases that are unique to your app.
211
+ contextualStrings: ["Carlsen", "Nepomniachtchi", "Praggnanandhaa"],
212
+ // [Default: undefined] Android-specific options to pass to the recognizer.
213
+ androidIntentOptions: {
214
+ EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS: 10000,
215
+ EXTRA_MASK_OFFENSIVE_WORDS: false,
216
+ },
217
+ // [Default: undefined] The package name of the speech recognition service to use.
218
+ androidRecognitionServicePackage: "com.google.android.tts",
219
+ // [Default: unspecified] The type of speech recognition being performed.
220
+ iosTaskHint: "unspecified", // "unspecified" | "dictation" | "search" | "confirmation"
221
+ // [Default: undefined] The audio session category and options to use.
222
+ iosCategory: {
223
+ category: "playAndRecord",
224
+ categoryOptions: ["defaultToSpeaker", "allowBluetooth"],
225
+ mode: "measurement",
226
+ },
227
+ // [Default: undefined] Recording options for Android & iOS
228
+ // For Android, this is only supported on Android 13 and above.
229
+ recordingOptions: {
230
+ // [Default: false] Whether to persist the audio to a local file path.
231
+ persist: false,
232
+ // [Default: FileSystem.CacheDirectory]
233
+ // Changes the default storage location for the audio file.
234
+ // e.g. `FileSystem.documentDirectory` (from `expo-file-system`)
235
+ outputDirectory: undefined,
236
+ // [Default: `"recording_${timestamp|uuid}.[wav|caf]"`]
237
+ // Changes the file name for the audio file.
238
+ // (you can retrieve the file path using `event.uri` on the `audiostart`/`audioend` events)
239
+ outputFileName: "recording.wav",
240
+ // [Default: undefined] The sample rate of the output audio file.
241
+ // Only supported on iOS
242
+ // Default sample rate is: 16000 on Android, 44100/48000 on iOS
243
+ outputSampleRate: undefined,
244
+ // [Default: undefined] The encoding of the output audio file.
245
+ // Only supported on iOS
246
+ outputEncoding: undefined,
247
+ },
248
+ // [Default: undefined] Use for file-based transcription.
249
+ audioSource: {
250
+ /** Local file URI, e.g. "file:///path/to/audio.wav" */
251
+ uri: undefined,
252
+ // [Android only] The number of channels in the source audio.
253
+ audioChannels: 1,
254
+ // [Android only] A value from AudioFormat - https://developer.android.com/reference/android/media/AudioFormat
255
+ audioEncoding: AudioEncodingAndroid.ENCODING_PCM_16BIT,
256
+ // [Android only] Audio sampling rate in Hz.
257
+ sampleRate: 16000,
258
+ // [Android only] The delay between chunks of audio to stream to the speech recognition service.
259
+ // Use this setting to avoid being rate-limited when using network-based recognition.
260
+ // Default: 50ms for network-based recognition, 15ms for on-device recognition
261
+ chunkDelayMillis: undefined,
262
+ },
263
+ });
264
+
265
+ // Stop capturing audio (and emit a final result if there is one)
266
+ ExpoSpeechRecognitionModule.stop();
267
+
268
+ // Immediately cancel speech recognition (does not process the final result)
269
+ ExpoSpeechRecognitionModule.abort();
270
+ ```
271
+
272
+ ## Speech Recognition Events
273
+
274
+ Events are largely based on the [Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition). The following events are supported:
275
+
276
+ | Event Name | Description | Notes |
277
+ | ------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
278
+ | `audiostart` | Audio capturing has started | Includes the `uri` if `recordingOptions.persist` is enabled. |
279
+ | `audioend` | Audio capturing has ended | Includes the `uri` if `recordingOptions.persist` is enabled. |
280
+ | `end` | Speech recognition service has disconnected. | This should be the last event dispatched. |
281
+ | `error` | Fired when a speech recognition error occurs. | You'll also receive an `error` event (with code "aborted") when calling `.abort()` |
282
+ | `nomatch` | Speech recognition service returns a final result with no significant recognition. | You may have non-final results recognized. This may get emitted after cancellation. |
283
+ | `result` | Speech recognition service returns a word or phrase has been positively recognized. | On Android, continous mode runs as a segmented session, meaning when a final result is reached, additional partial and final results will cover a new segment separate from the previous final result. On iOS, you should expect one final result before speech recognition has stopped. |
284
+ | `speechstart` | Fired when any sound — recognizable speech or not — has been detected | On iOS, this will fire once in the session after a result has occurred |
285
+ | `speechend` | Fired when speech recognized by the speech recognition service has stopped being detected. | Not supported yet on iOS |
286
+ | `start` | Speech recognition has started | Use this event to indicate to the user when to speak. |
287
+
288
+ ## Handling Errors
289
+
290
+ To handle errors, you can listen to the `error` event:
291
+
292
+ ```ts
293
+ import {
294
+ type ExpoSpeechRecognitionErrorCode,
295
+ addSpeechRecognitionListener,
296
+ useSpeechRecognitionEvent,
297
+ } from "expo-speech-recognition";
298
+
299
+ addSpeechRecognitionListener("error", (event) => {
300
+ console.log("error code:", event.error, "error messsage:", event.message);
301
+ });
302
+
303
+ // or through the `useSpeechRecognitionEvent` hook
304
+ useSpeechRecognitionEvent("error", (event) => {
305
+ console.log("error code:", event.error, "error messsage:", event.message);
306
+ });
307
+
308
+ // or through the `ExpoSpeechRecognitionErrorCode` type
309
+ const error: ExpoSpeechRecognitionErrorCode = "audio-capture";
310
+ ```
311
+
312
+ The error code is largely based on the Web Speech API error codes.
313
+
314
+ | Error Code | Description |
315
+ | ------------------------ | -------------------------------------------------------------------------- |
316
+ | `aborted` | The user called `ExpoSpeechRecognitionModule.abort()` |
317
+ | `audio-capture` | Audio recording error. |
318
+ | `bad-grammar` | Provided grammar is invalid. (Note: web only) |
319
+ | `language-not-supported` | Locale is not supported by the speech recognizer. |
320
+ | `network` | Network communication required for completing the recognition failed. |
321
+ | `no-speech` | No final speech was detected. |
322
+ | `not-allowed` | Permission to use speech recognition or microphone was not granted. |
323
+ | `service-not-allowed` | Recognizer is unavailable. |
324
+ | `busy` | The recognizer is busy and cannot accept any new recognition requests. |
325
+ | `client` | (Android) Unknown error. Corresponds with `SpeechRecognizer.ERROR_CLIENT`. |
326
+
327
+ ## Persisting Audio Recordings
328
+
329
+ If you would like to persist the recognized audio for later use, you can enable the `recordingOptions.persist` option when calling `start()`. Enabling this setting will emit an `{ uri: string }` event object in the `audiostart` and `audioend` events with the local file path.
330
+
331
+ > Note: For Android, this is only supported on Android 13 and above. Call `supportsRecording()` to see if it's available before using this feature.
332
+
333
+ Default audio output formats:
334
+
335
+ | Platform | Output Format | Notes |
336
+ | -------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
337
+ | Android | Linear PCM (16000 Hz, mono) | Suitable for processing on various external services (such as Google Speech API, Whisper, Deepgram, etc) |
338
+ | iOS | 32-bit Float PCM (44100/48000\* Hz, mono) | Default sample rate is device specific. Change this with `recordingOptions.outputSampleRate` and `recordingOptions.outputEncoding`. |
339
+
340
+ Example:
341
+
342
+ ```tsx
343
+ import { Button, View } from "react-native";
344
+ import {
345
+ ExpoSpeechRecognitionModule,
346
+ useSpeechRecognitionEvent,
347
+ } from "expo-speech-recognition";
348
+
349
+ function RecordAudio() {
350
+ const [recording, setRecording] = useState(false);
351
+ const [recordingUri, setRecordingUri] = useState<string | null>(null);
352
+
353
+ const handleStart = () => {
354
+ setRecording(true);
355
+ // Start recording
356
+ ExpoSpeechRecognitionModule.start({
357
+ lang: "en-US",
358
+ recordingOptions: {
359
+ persist: true,
360
+ // Optional: Specify the output file path to save the recording to
361
+ // e.g. `FileSystem.documentDirectory` (from `expo-file-system`)
362
+ outputDirectory:
363
+ "/data/user/0/expo.modules.speechrecognition.example/files",
364
+ // Optional: Specify the output file name to save the recording to
365
+ outputFileName: "recording.wav",
366
+ // Optional: Specify the output sample rate to save the recording to
367
+ // Only supported on iOS
368
+ // Default sample rate: 16000 on Android, 44100/48000 on iOS
369
+ outputSampleRate: 16000,
370
+ // Optional: Specify the output encoding to save the recording to
371
+ // Only supported on iOS
372
+ // Default encoding: pcmFormatInt16 on Android, pcmFormatFloat32 on iOS
373
+ outputEncoding: "pcmFormatInt16",
374
+ },
375
+ });
376
+ };
377
+
378
+ useSpeechRecognitionEvent("audiostart", (event) => {
379
+ // Note: don't use this file until the "audioend" event is emitted
380
+ // Note: event.uri will be null if `recordingOptions.persist` is not enabled
381
+ console.log("Recording started for file:", event.uri);
382
+ });
383
+
384
+ useSpeechRecognitionEvent("audioend", (event) => {
385
+ // Recording ended, the file is now safe to use
386
+ console.log("Local file path:", event.uri);
387
+ // Android: Will be saved as a .wav file
388
+ // e.g. "file:///data/user/0/expo.modules.speechrecognition.example/cache/recording_1720678500903.wav"
389
+ // iOS: Will be saved as a .caf file
390
+ // e.g. "file:///path/to/Library/Caches/audio_CD5E6C6C-3D9D-4754-9188-D6FAF97D9DF2.caf"
391
+ setRecordingPath(event.uri);
392
+ });
393
+
394
+ return (
395
+ <View>
396
+ <Button title="Start" onPress={handleStart} disabled={recording} />
397
+ {recordingUri && <AudioPlayer source={recordingUri} />}
398
+ </View>
399
+ );
400
+ }
401
+
402
+ // AudioPlayer.tsx
403
+ import { Button } from "react-native";
404
+ import { useAudioPlayer } from "expo-audio";
405
+
406
+ function AudioPlayer(props: { source: string }) {
407
+ const player = useAudioPlayer(props.source);
408
+ return <Button title="Play" onPress={player.play} />;
409
+ }
410
+ ```
411
+
412
+ ## Transcribing audio files
413
+
414
+ You can use the `audioSource.uri` option to transcribe audio files instead of using the microphone.
415
+
416
+ > **Important note**: This feature is available on Android 13+ and iOS. If the device does not support the feature, you'll receive an `error` event with the code `audio-capture`.
417
+
418
+ ### Supported input audio formats
419
+
420
+ #### Android
421
+
422
+ The following audio formats have been verified on a Samsung Galaxy S23 Ultra on Android 14:
423
+
424
+ - 16000hz 16-bit 1-channel PCM WAV ([example file](https://github.com/jamsch/expo-speech-recognition/blob/main/example/assets/audio-remote/remote-en-us-sentence-16000hz-pcm_s16le.wav))
425
+ - 16000hz MP3 1-channel ([example file](https://github.com/jamsch/expo-speech-recognition/blob/main/example/assets/audio-remote/remote-en-us-sentence-16000hz.mp3))
426
+ - 16000hz MP3 2-channel
427
+ - 16000hz ogg vorbis 1-channel ([example file](https://github.com/jamsch/expo-speech-recognition/blob/main/example/assets/audio-remote/remote-en-us-sentence-16000hz.ogg))
428
+
429
+ #### iOS
430
+
431
+ > Due to a limitation in the underlying `SFSpeechURLRecognitionRequest` API, file-based transcription will only transcribe the **first 1 minute of the audio file**.
432
+
433
+ The following audio formats have been verified on an iPhone 15 Pro Max on iOS 17.5:
434
+
435
+ - 16000hz 16-bit 1-channel PCM WAV ([example file](https://github.com/jamsch/expo-speech-recognition/blob/main/example/assets/audio-remote/remote-en-us-sentence-16000hz-pcm_s16le.wav))
436
+ - 16000hz MP3 1-channel ([example file](https://github.com/jamsch/expo-speech-recognition/blob/main/example/assets/audio-remote/remote-en-us-sentence-16000hz.mp3))
437
+
438
+ ### File transcription example
439
+
440
+ ```tsx
441
+ import { Button, View } from "react-native";
442
+ import {
443
+ ExpoSpeechRecognitionModule,
444
+ useSpeechRecognitionEvent,
445
+ AudioEncodingAndroid,
446
+ } from "expo-speech-recognition";
447
+
448
+ function TranscribeAudioFile() {
449
+ const [transcription, setTranscription] = useState("");
450
+
451
+ const handleTranscribe = () => {
452
+ ExpoSpeechRecognitionModule.start({
453
+ lang: "en-US",
454
+ interimResults: true,
455
+ audioSource: {
456
+ /** Local file URI */
457
+ uri: "file:///path/to/audio.wav",
458
+ /** [Android only] The number of channels in the source audio. */
459
+ audioChannels: 1,
460
+ /** [Android only] A value from AudioFormat - https://developer.android.com/reference/android/media/AudioFormat */
461
+ audioEncoding: AudioEncodingAndroid.ENCODING_PCM_16BIT,
462
+ /** [Android only] Audio sampling rate in Hz. */
463
+ sampleRate: 16000,
464
+ /**
465
+ * [Android only] The delay between chunks of audio to stream to the speech recognition service.
466
+ * Use this setting to avoid being rate-limited when using network-based recognition.
467
+ * If you're using on-device recognition, you may want to increase this value to avoid unprocessed audio chunks.
468
+ * Default: 50ms for network-based recognition, 15ms for on-device recognition
469
+ */
470
+ chunkDelayMillis: undefined,
471
+ },
472
+ });
473
+ };
474
+
475
+ useSpeechRecognitionEvent("result", (ev) => {
476
+ // Note: multiple final results will likely be returned on Android
477
+ // so you'll need to concatenate previous final results
478
+ setTranscription(ev.results[0]?.transcript || "");
479
+ });
480
+
481
+ return (
482
+ <View>
483
+ <Button title="Transcribe" onPress={handleTranscribe} />
484
+ <Text>{transcription}</Text>
485
+ </View>
486
+ );
487
+ }
488
+ ```
489
+
490
+ ## Polyfilling the Web SpeechRecognition API
491
+
492
+ > **Note: this is intended for projects that rely on third party libraries that use the Web Speech API**. If you're using this library directly, you should use the [Direct Module API](#direct-module-api) instead.
493
+
494
+ If you intend to polyfill the `webkitSpeechRecognition` or `SpeechRecognition` globals for use with external libraries, you can use the `ExpoWebSpeechRecognition` class to do so.
495
+
496
+ Refer to the [SpeechRecognition MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition) for usage. Note that some features (such as `grammars`) on some OSes aren't yet supported.
497
+
498
+ ```ts
499
+ // Import this polyfill for typings, as needed
500
+ // "npm install -D @types/dom-speech-recognition"
501
+ import "dom-speech-recognition";
502
+
503
+ import { ExpoWebSpeechRecognition } from "expo-speech-recognition";
504
+
505
+ // Polyfill the globals for use in external libraries
506
+ webkitSpeechRecognition = ExpoWebSpeechRecognition;
507
+ SpeechRecognition = ExpoWebSpeechRecognition;
508
+
509
+ // Usage is the same as the Web Speech API..
510
+ const recognition = new ExpoWebSpeechRecognition();
511
+
512
+ recognition.lang = "en-US";
513
+ // [Default: false] Note for iOS: final results are only available after speech recognition has stopped
514
+ recognition.interimResults = true;
515
+ recognition.maxAlternatives = 1;
516
+ // [Default: false] Continuous recognition. Note: if false on iOS, recognition will run until no speech is detected for 3 seconds
517
+ recognition.continuous = true;
518
+
519
+ // Custom (non-web) properties
520
+
521
+ recognition.contextualStrings = ["Carlsen", "Nepomniachtchi", "Praggnanandhaa"];
522
+ recognition.requiresOnDeviceRecognition = true;
523
+ recognition.addsPunctuation = true;
524
+ recognition.androidIntentOptions = {
525
+ EXTRA_LANGUAGE_MODEL: "web_search",
526
+ };
527
+ recognition.androidRecognitionServicePackage = "com.google.android.tts";
528
+
529
+ // Assign an event listener (note: this overwrites all event listeners)
530
+ recognition.onstart = (event) => console.log("started!");
531
+ recognition.onend = (event) => console.log("ended!");
532
+ recognition.onresult = (event) => {
533
+ console.log(
534
+ "result:",
535
+ event.results[event.resultIndex][0].transcript,
536
+ "final:",
537
+ event.results[event.resultIndex][0].isFinal,
538
+ );
539
+ };
540
+
541
+ // Or register an event listener
542
+ const handleStart = (event: Event) => console.log("started!");
543
+ recognition.registerEventListener("start", handleStart);
544
+ // and remember to unregister after you're done:
545
+ recognition.unregisterEventListener("start", handleStart);
546
+
547
+ const handleResult = (event: SpeechRecognitionEvent) => {
548
+ console.log("result:", event.results[event.resultIndex][0].transcript);
549
+ };
550
+
551
+ recognition.registerEventListener("result", handleResult);
552
+
553
+ recognition.registerEventListener("error", (event) => {
554
+ console.log("error code:", event.error, "error messsage:", event.message);
555
+ });
556
+
557
+ recognition.registerEventListener("end", (event) => console.log("ended!"));
558
+
559
+ // Start speech recognition
560
+ recognition.start();
561
+
562
+ // Stop speech recognition
563
+ recognition.stop();
564
+
565
+ // Immediately cancel speech recognition
566
+ recognition.abort();
567
+ ```
568
+
569
+ ## Muting the beep sound on Android
570
+
571
+ On Android, you may notice that there's a beep sound when you start and stop speech recognition. This is due to a hardcoded behavior in the underlying SpeechRecognizer API. However, a workaround you can use is by enabling continuous recognition:
572
+
573
+ ```ts
574
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
575
+
576
+ ExpoSpeechRecognitionModule.start({
577
+ lang: "en-US",
578
+ continuous: true,
579
+ });
580
+ ```
581
+
582
+ Under the hood, this sets the `EXTRA_AUDIO_SOURCE` in the recognizer intent to a custom microphone source instead of using the default microphone setting.
583
+
584
+ To maintain the same behavior as non-continuous mode, you should listen for a result event with `isFinal: true` and then immediately call `abort()` to stop the recognition.
585
+
586
+ ## Improving accuracy of single-word prompts
587
+
588
+ You may notice that after saying short syllables, words, letters, or numbers (e.g. "a", "b", 1, 5, etc.) that the speech recognition service may not return any results until you speak further. In order to improve the accuracy of single-word prompts for Android and iOS, you have the following options:
589
+
590
+ - For iOS, you can use the `iosTaskHint` option and set it to `confirmation`.
591
+ - For Android, the Google Development team [recommends to use the `web_search` language model for this specific issue](https://issuetracker.google.com/issues/280288200#comment28). You can change to that model (from the default `free_form`) by adding `androidIntentOptions: { EXTRA_LANGUAGE_MODEL: "web_search" }` to `ExpoSpeechRecognitionModule.start(...)`.
592
+ - For both platforms, you also may want to consider using on-device recognition. On Android this seems to work well for single-word prompts.
593
+ - Alternatively, you may want to consider recording the recognized audio and sending it to an external service for further processing. See [Persisting Audio Recordings](#persisting-audio-recordings) for more information. Note that some services (such as the Google Speech API) may require an audio file with a duration of at least 3 seconds.
594
+
595
+ ## Platform Compatibility Table
596
+
597
+ As of 7 Aug 2024, the following platforms are supported:
598
+
599
+ | Platform | Supported | Default Recognition Engine | Notes |
600
+ | ---------------------- | --------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
601
+ | Android (React Native) | ✅ | Google | Recording feature is only supported on Android 13 and above. Recognition engine can be changed via `androidRecognitionServicePackage` |
602
+ | iOS (React Native) | ✅ | Siri | |
603
+ | Chrome Desktop | ✅ | Google (server-based) | Implemented via prefix `webkitSpeechRecognition`. |
604
+ | Safari Desktop >= v16 | ✅ | Siri | Implemented via prefix `webkitSpeechRecognition`. Siri needs to be enabled |
605
+ | Chrome on Android | ✅ | Google | There's a few differences in how results get handled in comparison to the Chrome Desktop implementation |
606
+ | Chrome on iOS | ❌ | Google | Not working (Last tested 2023) |
607
+ | Edge on Windows | (unknown) | Azure | SpeechRecognition API is implemented, but requires the Azure speech component. Verify it’s presence at `edge://components` |
608
+ | Edge on Mac ARM | ❌ | Azure | SpeechRecognition API is implemented, but requires the Azure speech component. Verify it’s presence at `edge://components` |
609
+ | Brave Desktop | ❌ | - | As of Aug 2024, Brave is working on an implementation however there's currently no ETA (source: [brave-browser/issues/3725](https://github.com/brave/brave-browser/issues/3725#issuecomment-2224068859)) |
610
+ | Firefox Desktop | ❌ | - | No SpeechRecognition implementation |
611
+
612
+ ## API Methods
613
+
614
+ ### `start(options: SpeechRecognitionOptions): void`
615
+
616
+ Starts speech recognition.
617
+
618
+ ```ts
619
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
620
+
621
+ ExpoSpeechRecognitionModule.start({
622
+ lang: "en-US",
623
+ });
624
+ ```
625
+
626
+ ### `stop(): void`
627
+
628
+ Stops speech recognition and attempts to return a final result (through the `result` event).
629
+
630
+ ```ts
631
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
632
+
633
+ ExpoSpeechRecognitionModule.stop();
634
+ // Expect the following events to be emitted in order:
635
+ // One of:
636
+ // - A "result" event containing the final result,
637
+ // - A "nomatch" event if the final result was empty
638
+ // - A "error" event with the code "no-speech" if no speech was detected
639
+ // - "audioend" indicating the end of recording
640
+ // - "end" indicating the end of speech recognition
641
+ ```
642
+
643
+ ### `abort(): void`
644
+
645
+ Immediately cancels speech recognition (does not process the final result).
646
+
647
+ ```ts
648
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
649
+
650
+ ExpoSpeechRecognitionModule.abort();
651
+ // Expect an "error" event to be emitted with the code "aborted"
652
+ ```
653
+
654
+ ### `requestPermissionsAsync(): Promise<PermissionResponse>`
655
+
656
+ Presents a dialog to the user to request permissions for using speech recognition and the microphone.
657
+
658
+ For iOS, once a user has granted (or denied) location permissions by responding to the original permission request dialog,
659
+ the only way that the permissions can be changed is by the user themselves using the device settings app.
660
+
661
+ ```ts
662
+ import { requestPermissionsAsync } from "expo-speech-recognition";
663
+
664
+ requestPermissionsAsync().then((result) => {
665
+ console.log("Status:", result.status); // "granted" | "denied" | "not-determined"
666
+ console.log("Granted:", result.granted); // true | false
667
+ console.log("Can ask again:", result.canAskAgain); // true | false
668
+ console.log("Expires:", result.expires); // "never" | number
669
+ });
670
+ ```
671
+
672
+ ### `getPermissionsAsync(): Promise<PermissionResponse>`
673
+
674
+ Returns the current permission status for the microphone and speech recognition.
675
+
676
+ ```ts
677
+ import { getPermissionsAsync } from "expo-speech-recognition";
678
+
679
+ getPermissionsAsync().then((result) => {
680
+ console.log("Status:", result.status); // "granted" | "denied" | "not-determined"
681
+ console.log("Granted:", result.granted); // true | false
682
+ console.log("Can ask again:", result.canAskAgain); // true | false
683
+ console.log("Expires:", result.expires); // "never" | number
684
+ });
685
+ ```
686
+
687
+ ### `getStateAsync(): Promise<SpeechRecognitionState>`
688
+
689
+ Returns the current internal state of the speech recognizer.
690
+
691
+ ```ts
692
+ import { getStateAsync } from "expo-speech-recognition";
693
+
694
+ // Note: you probably should rather rely on the events emitted by the SpeechRecognition API instead
695
+ getStateAsync().then((state) => {
696
+ console.log("Current state:", state);
697
+ // "inactive" | "starting" | "stopping" | "recognizing"
698
+ });
699
+ ```
700
+
701
+ ### `addSpeechRecognitionListener(eventName: string, listener: (event: any) => void): { remove: () => void }`
702
+
703
+ ```ts
704
+ import { addSpeechRecognitionListener } from "expo-speech-recognition";
705
+
706
+ const listener = addSpeechRecognitionListener("result", (event) => {
707
+ console.log("result:", event.results[event.resultIndex][0].transcript);
708
+ });
709
+
710
+ // Remove the listener when you're done
711
+ listener.remove();
712
+ ```
713
+
714
+ ### `getSupportedLocales(): Promise<{ locales: string[]; installedLocales: string[] }>`
715
+
716
+ Get the list of supported locales and the installed locales that can be used for on-device speech recognition.
717
+
718
+ ```ts
719
+ import { getSupportedLocales } from "expo-speech-recognition";
720
+
721
+ getSupportedLocales({
722
+ /**
723
+ * The package name of the speech recognition service to use.
724
+ * If not provided, the default service used for on-device recognition will be used.
725
+ *
726
+ * Warning: the service package (such as Bixby) may not be able to return any results.
727
+ */
728
+ androidRecognitionServicePackage: "com.google.android.as",
729
+ })
730
+ .then((supportedLocales) => {
731
+ console.log("Supported locales:", supportedLocales.locales.join(", "));
732
+
733
+ // The on-device locales for the provided service package.
734
+ // Likely will be empty if it's not "com.google.android.as"
735
+ console.log(
736
+ "On-device locales:",
737
+ supportedLocales.installedLocales.join(", "),
738
+ );
739
+ })
740
+ .catch((error) => {
741
+ // If the service package is not found
742
+ // or there was an error retrieving the supported locales
743
+ console.error("Error getting supported locales:", error);
744
+ });
745
+ ```
746
+
747
+ ### `getSpeechRecognitionServices(): string[]` (Android only)
748
+
749
+ Get list of speech recognition services available on the device.
750
+
751
+ > Note: this only includes services that are listed under `androidSpeechServicePackages` in your app.json as well as the core services listed under `forceQueryable` when running the command: `adb shell dumpsys package queries`
752
+
753
+ ```ts
754
+ import { getSpeechRecognitionServices } from "expo-speech-recognition";
755
+
756
+ const packages = ExpoSpeechRecognitionModule.getSpeechRecognitionServices();
757
+ console.log("Speech recognition services:", packages.join(", "));
758
+ // e.g. ["com.google.android.as", "com.google.android.tts", "com.samsung.android.bixby.agent"]
759
+ ```
760
+
761
+ ### `getDefaultRecognitionService(): { packageName: string }` (Android only)
762
+
763
+ Returns the default voice recognition service on the device.
764
+
765
+ ```ts
766
+ import { getDefaultRecognitionService } from "expo-speech-recognition";
767
+
768
+ const service = ExpoSpeechRecognitionModule.getDefaultRecognitionService();
769
+ console.log("Default recognition service:", service.packageName);
770
+ // Usually this is "com.google.android.tts", however "com.google.android.as" will likely be used for on-device recognition.
771
+ ```
772
+
773
+ ### `getAssistantService(): { packageName: string }` (Android only)
774
+
775
+ Returns the default voice assistant service on the device.
776
+
777
+ ```ts
778
+ import { getAssistantService } from "expo-speech-recognition";
779
+
780
+ const service = ExpoSpeechRecognitionModule.getAssistantService();
781
+ console.log("Default assistant service:", service.packageName);
782
+ // Usually "com.google.android.googlequicksearchbox" for Google
783
+ // or "com.samsung.android.bixby.agent" for Samsung
784
+ ```
785
+
786
+ ### `supportsOnDeviceRecognition(): boolean`
787
+
788
+ Whether on-device speech recognition is available on the device.
789
+
790
+ ```ts
791
+ import { supportsOnDeviceRecognition } from "expo-speech-recognition";
792
+
793
+ const available = supportsOnDeviceRecognition();
794
+ console.log("OnDevice recognition available:", available);
795
+ ```
796
+
797
+ ### `supportsRecording(): boolean` (Android only)
798
+
799
+ Whether audio recording is supported during speech recognition. This mostly applies to Android devices, to check if it's at least Android 13.
800
+
801
+ ```ts
802
+ import { supportsRecording } from "expo-speech-recognition";
803
+
804
+ const available = supportsRecording();
805
+ console.log("Recording available:", available);
806
+ ```
807
+
808
+ ### `androidTriggerOfflineModelDownload({ locale: string }): Promise<{ status: "opened_dialog" | "download_success" | "download_canceled", message: string }>`
809
+
810
+ Users on Android devices will first need to download the offline model for the locale they want to use in order to use on-device speech recognition (i.e. the `requiresOnDeviceRecognition` setting in the `start` options).
811
+
812
+ You can see which locales are supported and installed on your device by running `getSupportedLocales()`.
813
+
814
+ To download the offline model for a specific locale, use the `androidTriggerOfflineModelDownload` function.
815
+
816
+ ```ts
817
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
818
+
819
+ // Download the offline model for the specified locale
820
+ ExpoSpeechRecognitionModule.androidTriggerOfflineModelDownload({
821
+ locale: "en-US",
822
+ })
823
+ .then((result) => {
824
+ switch (result.status) {
825
+ case "opened_dialog":
826
+ // On Android 13, the status will be "opened_dialog" indicating that the model download dialog was opened.
827
+ console.log("Offline model download dialog opened.");
828
+ break;
829
+ case "download_success":
830
+ // On Android 14+, model was succesfully downloaded.
831
+ console.log("Offline model downloaded successfully!");
832
+ break;
833
+ case "download_canceled":
834
+ // On Android 14+, the download was canceled by a user interaction.
835
+ console.log("Offline model download was canceled.");
836
+ break;
837
+ })
838
+ .catch((err) => {
839
+ console.log("Failed to download offline model!", err.message);
840
+ });
841
+ ```
842
+
843
+ The device will display a dialog to download the model. Once the model is downloaded, you can use the `getSupportedLocales` function to get the list of installed locales.
844
+
845
+ ![On Device Recognition](./images/on-device-recognition.jpg)
846
+
847
+ ### `setCategoryIOS({...}): void` (iOS only)
848
+
849
+ This function is an implementation of [AVAudioSession.setCategory](https://developer.apple.com/documentation/avfaudio/avaudiosession/1771734-setcategory) for iOS. For multimedia applications, you may want to set the audio session category and mode to control the audio routing.
850
+
851
+ > Note: when starting speech recognition, audio session category is changed to `playAndRecord` with option `defaultToSpeaker` and `allowBluetooth` and mode `measurement`. You can instead configure the audio session category and mode by passing the `iosCategory` option to the `start` function.
852
+
853
+ ```ts
854
+ import {
855
+ setCategoryIOS,
856
+ AVAudioSessionCategory,
857
+ AVAudioSessionCategoryOptions,
858
+ AVAudioSessionMode,
859
+ } from "expo-speech-recognition";
860
+
861
+ setCategoryIOS({
862
+ category: AVAudioSessionCategory.playAndRecord, // or "playAndRecord"
863
+ categoryOptions: [
864
+ AVAudioSessionCategoryOptions.defaultToSpeaker,
865
+ AVAudioSessionCategoryOptions.allowBluetooth,
866
+ ],
867
+ mode: AVAudioSessionMode.default,
868
+ });
869
+ ```
870
+
871
+ ### `getAudioSessionCategoryAndOptionsIOS()` (iOS only)
872
+
873
+ Returns the current audio session category and options. For advanced use cases, you may want to use this function to safely configure the audio session category and mode.
874
+
875
+ ```ts
876
+ import { getAudioSessionCategoryAndOptionsIOS } from "expo-speech-recognition";
877
+
878
+ const values = getAudioSessionCategoryAndOptionsIOS();
879
+ console.log(values);
880
+ // { category: "playAndRecord", categoryOptions: ["defaultToSpeaker", "allowBluetooth"], mode: "measurement" }
881
+ ```
882
+
883
+ ### `setAudioSessionActiveIOS(value: boolean, options?: { notifyOthersOnDeactivation: boolean }): void`
884
+
885
+ Sets the audio session active state.
886
+
887
+ ```ts
888
+ import { setAudioSessionActiveIOS } from "expo-speech-recognition";
889
+
890
+ setAudioSessionActiveIOS(true, {
891
+ notifyOthersOnDeactivation: true,
892
+ });
893
+ ```