expo-speech-recognition 0.2.21 → 0.2.24
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.
- package/LICENSE +21 -0
- package/README.md +71 -16
- package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionModule.kt +20 -12
- package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionOptions.kt +11 -0
- package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechService.kt +20 -0
- package/app.plugin.js +18 -12
- package/build/ExpoSpeechRecognitionModule.types.d.ts +31 -1
- package/build/ExpoSpeechRecognitionModule.types.d.ts.map +1 -1
- package/build/ExpoSpeechRecognitionModule.types.js.map +1 -1
- package/ios/ExpoSpeechRecognitionException.swift +6 -6
- package/ios/ExpoSpeechRecognitionModule.swift +36 -6
- package/ios/ExpoSpeechRecognizer.swift +115 -14
- package/ios/SpeechRecognitionOptions.swift +11 -0
- package/package.json +1 -1
- package/src/ExpoSpeechRecognitionModule.types.ts +32 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 jamsch
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -19,6 +19,8 @@ expo-speech-recognition implements the iOS [`SFSpeechRecognizer`](https://develo
|
|
|
19
19
|
- [Transcribing audio files](#transcribing-audio-files)
|
|
20
20
|
- [Supported input audio formats](#supported-input-audio-formats)
|
|
21
21
|
- [File transcription example](#file-transcription-example)
|
|
22
|
+
- [Volume metering](#volume-metering)
|
|
23
|
+
- [Volume metering example](#volume-metering-example)
|
|
22
24
|
- [Polyfilling the Web SpeechRecognition API](#polyfilling-the-web-speechrecognition-api)
|
|
23
25
|
- [Muting the beep sound on Android](#muting-the-beep-sound-on-android)
|
|
24
26
|
- [Improving accuracy of single-word prompts](#improving-accuracy-of-single-word-prompts)
|
|
@@ -58,23 +60,29 @@ npm install expo-speech-recognition
|
|
|
58
60
|
|
|
59
61
|
> 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.
|
|
60
62
|
|
|
63
|
+
To configure `androidSpeechServicePackages`, add additional speech service packages here that aren't listed under the `forceQueryable` section when running the command: `adb shell dumpsys package queries`.
|
|
64
|
+
|
|
61
65
|
```js
|
|
62
66
|
// app.json
|
|
63
67
|
{
|
|
64
68
|
"expo": {
|
|
65
69
|
"plugins": [
|
|
70
|
+
"plugin-one",
|
|
71
|
+
"plugin-two",
|
|
72
|
+
|
|
73
|
+
// no config (v0.2.22+)
|
|
74
|
+
"expo-speech-recognition",
|
|
75
|
+
|
|
76
|
+
// or with config
|
|
66
77
|
[
|
|
67
78
|
"expo-speech-recognition",
|
|
68
79
|
{
|
|
69
80
|
"microphonePermission": "Allow $(PRODUCT_NAME) to use the microphone.",
|
|
70
81
|
"speechRecognitionPermission": "Allow $(PRODUCT_NAME) to use speech recognition.",
|
|
71
|
-
// Add additional speech service packages here that aren't listed
|
|
72
|
-
// under the `forceQueryable` section when running the command:
|
|
73
|
-
// "adb shell dumpsys package queries"
|
|
74
|
-
// default: ["com.google.android.googlequicksearchbox"]
|
|
75
82
|
"androidSpeechServicePackages": ["com.google.android.googlequicksearchbox"]
|
|
76
83
|
}
|
|
77
84
|
]
|
|
85
|
+
// rest of your plugins
|
|
78
86
|
]
|
|
79
87
|
}
|
|
80
88
|
}
|
|
@@ -231,7 +239,9 @@ ExpoSpeechRecognitionModule.start({
|
|
|
231
239
|
// The maximum number of alternative transcriptions to return.
|
|
232
240
|
maxAlternatives: 1,
|
|
233
241
|
// [Default: false] Continuous recognition.
|
|
234
|
-
// If false
|
|
242
|
+
// If false:
|
|
243
|
+
// - on iOS 17-, recognition will run until no speech is detected for 3 seconds.
|
|
244
|
+
// - on iOS 18+ and Android, recognition will run until a final result is received.
|
|
235
245
|
// Not supported on Android 12 and below.
|
|
236
246
|
continuous: true,
|
|
237
247
|
// [Default: false] Prevent device from sending audio over the network. Only enabled if the device supports it.
|
|
@@ -291,6 +301,13 @@ ExpoSpeechRecognitionModule.start({
|
|
|
291
301
|
// Default: 50ms for network-based recognition, 15ms for on-device recognition
|
|
292
302
|
chunkDelayMillis: undefined,
|
|
293
303
|
},
|
|
304
|
+
// Settings for volume change events.
|
|
305
|
+
volumeChangeEventOptions: {
|
|
306
|
+
// [Default: false] Whether to emit the `volumechange` events when the input volume changes.
|
|
307
|
+
enabled: false,
|
|
308
|
+
// [Default: 100ms on iOS] The interval (in milliseconds) to emit `volumechange` events.
|
|
309
|
+
intervalMillis: 300,
|
|
310
|
+
},
|
|
294
311
|
});
|
|
295
312
|
|
|
296
313
|
// Stop capturing audio (and emit a final result if there is one)
|
|
@@ -304,17 +321,18 @@ ExpoSpeechRecognitionModule.abort();
|
|
|
304
321
|
|
|
305
322
|
Events are largely based on the [Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition). The following events are supported:
|
|
306
323
|
|
|
307
|
-
| Event Name
|
|
308
|
-
|
|
|
309
|
-
| `audiostart`
|
|
310
|
-
| `audioend`
|
|
311
|
-
| `end`
|
|
312
|
-
| `error`
|
|
313
|
-
| `nomatch`
|
|
314
|
-
| `result`
|
|
315
|
-
| `speechstart`
|
|
316
|
-
| `speechend`
|
|
317
|
-
| `start`
|
|
324
|
+
| Event Name | Description | Notes |
|
|
325
|
+
| -------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
326
|
+
| `audiostart` | Audio capturing has started | Includes the `uri` if `recordingOptions.persist` is enabled. |
|
|
327
|
+
| `audioend` | Audio capturing has ended | Includes the `uri` if `recordingOptions.persist` is enabled. |
|
|
328
|
+
| `end` | Speech recognition service has disconnected. | This should always be the last event dispatched, including after errors. |
|
|
329
|
+
| `error` | Fired when a speech recognition error occurs. | You'll also receive an `error` event (with code "aborted") when calling `.abort()` |
|
|
330
|
+
| `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. |
|
|
331
|
+
| `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. |
|
|
332
|
+
| `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 |
|
|
333
|
+
| `speechend` | Fired when speech recognized by the speech recognition service has stopped being detected. | Not supported yet on iOS |
|
|
334
|
+
| `start` | Speech recognition has started | Use this event to indicate to the user when to speak. |
|
|
335
|
+
| `volumechange` | Fired when the input volume changes. | Returns a value between -2 and 10 indicating the volume of the input audio. Consider anything below 0 to be inaudible. |
|
|
318
336
|
|
|
319
337
|
## Handling Errors
|
|
320
338
|
|
|
@@ -522,6 +540,43 @@ function TranscribeAudioFile() {
|
|
|
522
540
|
}
|
|
523
541
|
```
|
|
524
542
|
|
|
543
|
+
## Volume metering
|
|
544
|
+
|
|
545
|
+
You can use the `volumeChangeEventOptions.enabled` option to enable volume metering. This will emit a `volumechange` event with the current volume level (between -2 and 10) as a value. You can use this value to animate the volume metering of a user's voice, or to provide feedback to the user about the volume level.
|
|
546
|
+
|
|
547
|
+
### Volume metering example
|
|
548
|
+
|
|
549
|
+

|
|
550
|
+
|
|
551
|
+
See: [VolumeMeteringAvatar.tsx](https://github.com/jamsch/expo-speech-recognition/tree/main/example/components/VolumeMeteringAvatar.tsx) for a complete example that involves using `react-native-reanimated` to animate the volume metering.
|
|
552
|
+
|
|
553
|
+
```tsx
|
|
554
|
+
import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
|
|
555
|
+
|
|
556
|
+
function VolumeMeteringAvatar() {
|
|
557
|
+
useSpeechRecognitionEvent("volumechange", (event) => {
|
|
558
|
+
console.log("Volume changed to:", event.value);
|
|
559
|
+
});
|
|
560
|
+
|
|
561
|
+
const handleStart = () => {
|
|
562
|
+
ExpoSpeechRecognitionModule.start({
|
|
563
|
+
lang: "en-US",
|
|
564
|
+
volumeChangeEventOptions: {
|
|
565
|
+
enabled: true,
|
|
566
|
+
intervalMillis: 300,
|
|
567
|
+
},
|
|
568
|
+
});
|
|
569
|
+
};
|
|
570
|
+
|
|
571
|
+
return (
|
|
572
|
+
<View>
|
|
573
|
+
<Button title="Start" onPress={handleStart} />
|
|
574
|
+
<Text>Volume: {volume}</Text>
|
|
575
|
+
</View>
|
|
576
|
+
);
|
|
577
|
+
}
|
|
578
|
+
```
|
|
579
|
+
|
|
525
580
|
## Polyfilling the Web SpeechRecognition API
|
|
526
581
|
|
|
527
582
|
> [!IMPORTANT]
|
|
@@ -86,6 +86,8 @@ class ExpoSpeechRecognitionModule : Module() {
|
|
|
86
86
|
"start",
|
|
87
87
|
// Called when there's results (as a string array, not API compliant)
|
|
88
88
|
"results",
|
|
89
|
+
// Fired when the input volume changes
|
|
90
|
+
"volumechange",
|
|
89
91
|
)
|
|
90
92
|
|
|
91
93
|
Function("getDefaultRecognitionService") {
|
|
@@ -325,26 +327,32 @@ class ExpoSpeechRecognitionModule : Module() {
|
|
|
325
327
|
promise: Promise,
|
|
326
328
|
) {
|
|
327
329
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
|
328
|
-
promise.resolve(
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
330
|
+
promise.resolve(
|
|
331
|
+
mapOf(
|
|
332
|
+
"locales" to mutableListOf<String>(),
|
|
333
|
+
"installedLocales" to mutableListOf<String>(),
|
|
334
|
+
),
|
|
335
|
+
)
|
|
332
336
|
return
|
|
333
337
|
}
|
|
334
338
|
|
|
335
339
|
if (options.androidRecognitionServicePackage == null && !SpeechRecognizer.isOnDeviceRecognitionAvailable(appContext)) {
|
|
336
|
-
promise.resolve(
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
+
promise.resolve(
|
|
341
|
+
mapOf(
|
|
342
|
+
"locales" to mutableListOf<String>(),
|
|
343
|
+
"installedLocales" to mutableListOf<String>(),
|
|
344
|
+
),
|
|
345
|
+
)
|
|
340
346
|
return
|
|
341
347
|
}
|
|
342
348
|
|
|
343
349
|
if (options.androidRecognitionServicePackage != null && !SpeechRecognizer.isRecognitionAvailable(appContext)) {
|
|
344
|
-
promise.resolve(
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
350
|
+
promise.resolve(
|
|
351
|
+
mapOf(
|
|
352
|
+
"locales" to mutableListOf<String>(),
|
|
353
|
+
"installedLocales" to mutableListOf<String>(),
|
|
354
|
+
),
|
|
355
|
+
)
|
|
348
356
|
return
|
|
349
357
|
}
|
|
350
358
|
|
package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionOptions.kt
CHANGED
|
@@ -50,6 +50,17 @@ class SpeechRecognitionOptions : Record {
|
|
|
50
50
|
|
|
51
51
|
@Field
|
|
52
52
|
val iosCategory: Map<String, Any>? = null
|
|
53
|
+
|
|
54
|
+
@Field
|
|
55
|
+
val volumeChangeEventOptions: VolumeChangeEventOptions? = null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
class VolumeChangeEventOptions : Record {
|
|
59
|
+
@Field
|
|
60
|
+
val enabled: Boolean? = false
|
|
61
|
+
|
|
62
|
+
@Field
|
|
63
|
+
val intervalMillis: Int? = null
|
|
53
64
|
}
|
|
54
65
|
|
|
55
66
|
class RecordingOptions : Record {
|
|
@@ -50,6 +50,9 @@ class ExpoSpeechService(
|
|
|
50
50
|
private var speech: SpeechRecognizer? = null
|
|
51
51
|
private val mainHandler = Handler(Looper.getMainLooper())
|
|
52
52
|
|
|
53
|
+
private lateinit var options: SpeechRecognitionOptions
|
|
54
|
+
private var lastVolumeChangeEventTime: Long = 0L
|
|
55
|
+
|
|
53
56
|
/** Audio recorder for persisting audio */
|
|
54
57
|
private var audioRecorder: ExpoAudioRecorder? = null
|
|
55
58
|
|
|
@@ -108,6 +111,7 @@ class ExpoSpeechService(
|
|
|
108
111
|
|
|
109
112
|
/** Starts speech recognition */
|
|
110
113
|
fun start(options: SpeechRecognitionOptions) {
|
|
114
|
+
this.options = options
|
|
111
115
|
mainHandler.post {
|
|
112
116
|
log("Start recognition.")
|
|
113
117
|
|
|
@@ -119,6 +123,7 @@ class ExpoSpeechService(
|
|
|
119
123
|
delayedFileStreamer = null
|
|
120
124
|
recognitionState = RecognitionState.STARTING
|
|
121
125
|
soundState = SoundState.INACTIVE
|
|
126
|
+
lastVolumeChangeEventTime = 0L
|
|
122
127
|
try {
|
|
123
128
|
val intent = createSpeechIntent(options)
|
|
124
129
|
speech = createSpeechRecognizer(options)
|
|
@@ -454,6 +459,21 @@ class ExpoSpeechService(
|
|
|
454
459
|
}
|
|
455
460
|
|
|
456
461
|
override fun onRmsChanged(rmsdB: Float) {
|
|
462
|
+
if (options.volumeChangeEventOptions?.enabled != true) {
|
|
463
|
+
return
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
val intervalMs = options.volumeChangeEventOptions?.intervalMillis
|
|
467
|
+
|
|
468
|
+
if (intervalMs == null) {
|
|
469
|
+
sendEvent("volumechange", mapOf("value" to rmsdB))
|
|
470
|
+
} else {
|
|
471
|
+
val currentTime = System.currentTimeMillis()
|
|
472
|
+
if (currentTime - lastVolumeChangeEventTime >= intervalMs) {
|
|
473
|
+
sendEvent("volumechange", mapOf("value" to rmsdB))
|
|
474
|
+
lastVolumeChangeEventTime = currentTime
|
|
475
|
+
}
|
|
476
|
+
}
|
|
457
477
|
/*
|
|
458
478
|
val isSilent = rmsdB <= 0
|
|
459
479
|
|
package/app.plugin.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// @ts-check
|
|
1
2
|
const {
|
|
2
3
|
withAndroidManifest,
|
|
3
4
|
AndroidConfig,
|
|
@@ -6,7 +7,7 @@ const {
|
|
|
6
7
|
} = require("expo/config-plugins");
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
|
-
* @type {import("expo/config-plugins").ConfigPlugin<{ packages
|
|
10
|
+
* @type {import("expo/config-plugins").ConfigPlugin<{ packages?: string[] }>}
|
|
10
11
|
*/
|
|
11
12
|
const withAndroidPackageVisibilityFiltering = (config, { packages = [] }) => {
|
|
12
13
|
return withAndroidManifest(config, (config) => {
|
|
@@ -35,22 +36,27 @@ const withAndroidPackageVisibilityFiltering = (config, { packages = [] }) => {
|
|
|
35
36
|
</intent>
|
|
36
37
|
</queries>
|
|
37
38
|
*/
|
|
38
|
-
|
|
39
|
+
|
|
40
|
+
for (const pkg of allPackages) {
|
|
39
41
|
if (
|
|
40
42
|
!config.modResults.manifest.queries.some(
|
|
41
43
|
(query) => query.package?.[0]?.$?.["android:name"] === pkg,
|
|
42
44
|
)
|
|
43
45
|
) {
|
|
44
46
|
config.modResults.manifest.queries.push({
|
|
45
|
-
package: { $: { "android:name": pkg } },
|
|
46
|
-
intent:
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
package: [{ $: { "android:name": pkg } }],
|
|
48
|
+
intent: [
|
|
49
|
+
{
|
|
50
|
+
action: [
|
|
51
|
+
{
|
|
52
|
+
$: { "android:name": "android.speech.RecognitionService" },
|
|
53
|
+
},
|
|
54
|
+
],
|
|
49
55
|
},
|
|
50
|
-
|
|
56
|
+
],
|
|
51
57
|
});
|
|
52
58
|
}
|
|
53
|
-
}
|
|
59
|
+
}
|
|
54
60
|
|
|
55
61
|
return config;
|
|
56
62
|
});
|
|
@@ -61,7 +67,7 @@ const withAndroidPackageVisibilityFiltering = (config, { packages = [] }) => {
|
|
|
61
67
|
* microphonePermission?: string;
|
|
62
68
|
* speechRecognitionPermission?: string;
|
|
63
69
|
* androidSpeechServicePackages?: string[];
|
|
64
|
-
* }>}
|
|
70
|
+
* }|undefined>}
|
|
65
71
|
*/
|
|
66
72
|
const withExpoSpeechRecognition = (config, props) => {
|
|
67
73
|
if (!config.ios) {
|
|
@@ -73,12 +79,12 @@ const withExpoSpeechRecognition = (config, props) => {
|
|
|
73
79
|
}
|
|
74
80
|
|
|
75
81
|
config.ios.infoPlist.NSSpeechRecognitionUsageDescription =
|
|
76
|
-
props
|
|
82
|
+
props?.speechRecognitionPermission ||
|
|
77
83
|
config.ios.infoPlist.NSSpeechRecognitionUsageDescription ||
|
|
78
84
|
"Allow $(PRODUCT_NAME) to use speech recognition.";
|
|
79
85
|
|
|
80
86
|
config.ios.infoPlist.NSMicrophoneUsageDescription =
|
|
81
|
-
props
|
|
87
|
+
props?.microphonePermission ||
|
|
82
88
|
config.ios.infoPlist.NSMicrophoneUsageDescription ||
|
|
83
89
|
"Allow $(PRODUCT_NAME) to use the microphone.";
|
|
84
90
|
|
|
@@ -92,7 +98,7 @@ const withExpoSpeechRecognition = (config, props) => {
|
|
|
92
98
|
[
|
|
93
99
|
withAndroidPackageVisibilityFiltering,
|
|
94
100
|
{
|
|
95
|
-
packages: props
|
|
101
|
+
packages: props?.androidSpeechServicePackages,
|
|
96
102
|
},
|
|
97
103
|
],
|
|
98
104
|
]);
|
|
@@ -109,6 +109,14 @@ export type ExpoSpeechRecognitionNativeEventMap = {
|
|
|
109
109
|
end: null;
|
|
110
110
|
soundstart: null;
|
|
111
111
|
soundend: null;
|
|
112
|
+
volumechange: {
|
|
113
|
+
/**
|
|
114
|
+
* A float value between -2 and 10 indicating the volume of the input audio
|
|
115
|
+
*
|
|
116
|
+
* Consider anything below 0 to be inaudible
|
|
117
|
+
*/
|
|
118
|
+
value: number;
|
|
119
|
+
};
|
|
112
120
|
};
|
|
113
121
|
export type ExpoSpeechRecognitionOptions = {
|
|
114
122
|
/** [Default: "en-US"] The language of the speech recognition */
|
|
@@ -130,7 +138,10 @@ export type ExpoSpeechRecognitionOptions = {
|
|
|
130
138
|
*
|
|
131
139
|
* Not supported on Android 12 and below.
|
|
132
140
|
*
|
|
133
|
-
* If false
|
|
141
|
+
* If false, the behaviors are the following:
|
|
142
|
+
*
|
|
143
|
+
* - on iOS 17-, recognition will run until no speech is detected for 3 seconds.
|
|
144
|
+
* - on iOS 18+ and Android, recognition will run until a result with `isFinal: true` is received.
|
|
134
145
|
*/
|
|
135
146
|
continuous?: boolean;
|
|
136
147
|
/** [Default: false] Prevent device from sending audio over the network. Only enabled if the device supports it.
|
|
@@ -207,6 +218,25 @@ export type ExpoSpeechRecognitionOptions = {
|
|
|
207
218
|
* Docs: https://developer.apple.com/documentation/avfaudio/avaudiosession/category
|
|
208
219
|
*/
|
|
209
220
|
iosCategory?: SetCategoryOptions;
|
|
221
|
+
/**
|
|
222
|
+
* Settings for volume change events.
|
|
223
|
+
*/
|
|
224
|
+
volumeChangeEventOptions?: {
|
|
225
|
+
/**
|
|
226
|
+
* Whether to emit volume change events.
|
|
227
|
+
*
|
|
228
|
+
* Default: false
|
|
229
|
+
*/
|
|
230
|
+
enabled?: boolean;
|
|
231
|
+
/**
|
|
232
|
+
* Specifies the interval (in milliseconds) to emit `volumechange` events.
|
|
233
|
+
*
|
|
234
|
+
* Default: 100ms on iOS
|
|
235
|
+
*
|
|
236
|
+
* Increasing this value will improve performance
|
|
237
|
+
*/
|
|
238
|
+
intervalMillis?: number;
|
|
239
|
+
};
|
|
210
240
|
};
|
|
211
241
|
export type IOSTaskHintValue = (typeof TaskHintIOS)[keyof typeof TaskHintIOS];
|
|
212
242
|
export type RecordingOptions = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExpoSpeechRecognitionModule.types.d.ts","sourceRoot":"","sources":["../src/ExpoSpeechRecognitionModule.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,OAAO,KAAK,EACV,oBAAoB,EACpB,sBAAsB,EACtB,6BAA6B,EAC7B,kBAAkB,EAClB,oCAAoC,EACpC,kCAAkC,EAClC,WAAW,EACZ,MAAM,aAAa,CAAC;AAErB,MAAM,MAAM,2BAA2B,GACrC,CAAC,OAAO,sBAAsB,CAAC,CAAC,MAAM,OAAO,sBAAsB,CAAC,CAAC;AAEvE,MAAM,MAAM,2BAA2B,GAAG;IACxC,UAAU,EAAE,MAAM,CAAC;IACnB;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;;;;;;;;;;;OAeG;IACH,QAAQ,EAAE,kCAAkC,EAAE,CAAC;CAChD,CAAC;AAEF,MAAM,MAAM,kCAAkC,GAAG;IAC/C,sDAAsD;IACtD,eAAe,EAAE,MAAM,CAAC;IACxB,oDAAoD;IACpD,aAAa,EAAE,MAAM,CAAC;IACtB,6DAA6D;IAC7D,OAAO,EAAE,MAAM,CAAC;IAChB,qHAAqH;IACrH,UAAU,EAAE,MAAM,CAAC;CACpB,CA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,CAAC;QACV;;;;WAIG;QACH,MAAM,EAAE,kBAAkB,GAAG,eAAe,GAAG,mBAAmB,CAAC;QACnE,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC,CAAC;IACH;;;;OAIG;IACH,cAAc,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAAC;IAElD;;;;;;;OAOG;IACH,oCAAoC,IAAI;QACtC,QAAQ,EAAE,2BAA2B,CAAC;QACtC,eAAe,EAAE,kCAAkC,EAAE,CAAC;QACtD,IAAI,EAAE,uBAAuB,CAAC;KAC/B,CAAC;IACF;;;;;;OAMG;IACH,wBAAwB,CACtB,KAAK,EAAE,OAAO,EACd,OAAO,CAAC,EAAE;QACR,4FAA4F;QAC5F,0BAA0B,EAAE,OAAO,CAAC;KACrC,GACA,IAAI,CAAC;IACR;;OAEG;IACH,aAAa,IAAI,OAAO,CAAC,sBAAsB,CAAC,CAAC;CAClD;AAED,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,EAAE,2BAA2B,CAAC;IACtC,eAAe,EAAE,kCAAkC,EAAE,CAAC;IACtD,IAAI,CAAC,EAAE,uBAAuB,CAAC;CAChC,CAAC;AAEF,KAAK,sBAAsB,GACvB,UAAU,GACV,UAAU,GACV,aAAa,GACb,UAAU,CAAC;AAEf;;;;GAIG;AACH,MAAM,MAAM,kCAAkC,GAC5C,CAAC,OAAO,6BAA6B,CAAC,CAAC,MAAM,OAAO,6BAA6B,CAAC,CAAC;AAErF;;;;GAIG;AACH,MAAM,MAAM,uBAAuB,GACjC,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,OAAO,kBAAkB,CAAC,CAAC"}
|
|
@@ -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};\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 on iOS, recognition will run until no speech is detected for 3 seconds.\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\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 \"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"]}
|
|
@@ -26,7 +26,7 @@ language-not-supported
|
|
|
26
26
|
The user agent does not support the language specified in the value of lang attribute of the SpeechRecognition object. The set of supported languages is browser-dependent, and from frontend code there is no way to programmatically determine what languages a user's browser supports for speech recognition.
|
|
27
27
|
*/
|
|
28
28
|
|
|
29
|
-
internal class NilRecognizerException: Exception {
|
|
29
|
+
internal final class NilRecognizerException: Exception {
|
|
30
30
|
override var code: String {
|
|
31
31
|
"audio-capture"
|
|
32
32
|
}
|
|
@@ -36,7 +36,7 @@ internal class NilRecognizerException: Exception {
|
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
internal class PermissionException: Exception {
|
|
39
|
+
internal final class PermissionException: Exception {
|
|
40
40
|
override var code: String {
|
|
41
41
|
"not-allowed"
|
|
42
42
|
}
|
|
@@ -45,7 +45,7 @@ internal class PermissionException: Exception {
|
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
internal class NotAuthorizedException: Exception {
|
|
48
|
+
internal final class NotAuthorizedException: Exception {
|
|
49
49
|
override var code: String {
|
|
50
50
|
"not-allowed"
|
|
51
51
|
}
|
|
@@ -55,7 +55,7 @@ internal class NotAuthorizedException: Exception {
|
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
internal class NotPermittedToRecordException: Exception {
|
|
58
|
+
internal final class NotPermittedToRecordException: Exception {
|
|
59
59
|
override var code: String {
|
|
60
60
|
"not-allowed"
|
|
61
61
|
}
|
|
@@ -64,7 +64,7 @@ internal class NotPermittedToRecordException: Exception {
|
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
internal class InvalidAudioModeException: GenericException<String> {
|
|
67
|
+
internal final class InvalidAudioModeException: GenericException<String> {
|
|
68
68
|
override var code: String {
|
|
69
69
|
"audio-capture"
|
|
70
70
|
}
|
|
@@ -73,7 +73,7 @@ internal class InvalidAudioModeException: GenericException<String> {
|
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
-
internal class RecognizerUnavilableException: Exception {
|
|
76
|
+
internal final class RecognizerUnavilableException: Exception {
|
|
77
77
|
override var code: String {
|
|
78
78
|
"service-not-allowed"
|
|
79
79
|
}
|
|
@@ -41,6 +41,14 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
41
41
|
// This is a temporary workaround until the issue is fixed in a future iOS release
|
|
42
42
|
var hasSeenFinalResult: Bool = false
|
|
43
43
|
|
|
44
|
+
// Hack for iOS 18 to avoid sending a "nomatch" event after the final-final result
|
|
45
|
+
// Example event order emitted in iOS 18:
|
|
46
|
+
// [
|
|
47
|
+
// { isFinal: false, transcripts: ["actually", "final", "results"], metadata: { duration: 1500 } },
|
|
48
|
+
// { isFinal: true, transcripts: [] }
|
|
49
|
+
// ]
|
|
50
|
+
var previousResult: SFSpeechRecognitionResult?
|
|
51
|
+
|
|
44
52
|
public func definition() -> ModuleDefinition {
|
|
45
53
|
// Sets the name of the module that JavaScript code will use to refer to the module. Takes a string as an argument.
|
|
46
54
|
// Can be inferred from module's class name, but it's recommended to set it explicitly for clarity.
|
|
@@ -85,7 +93,9 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
85
93
|
// intent to recognize grammars associated with the current SpeechRecognition
|
|
86
94
|
"start",
|
|
87
95
|
// Called when there's results (as a string array, not API compliant)
|
|
88
|
-
"result"
|
|
96
|
+
"result",
|
|
97
|
+
// Fired when the input volume changes
|
|
98
|
+
"volumechange"
|
|
89
99
|
)
|
|
90
100
|
|
|
91
101
|
OnCreate {
|
|
@@ -130,6 +140,9 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
130
140
|
do {
|
|
131
141
|
let currentLocale = await speechRecognizer?.getLocale()
|
|
132
142
|
|
|
143
|
+
// Reset the previous result
|
|
144
|
+
self.previousResult = nil
|
|
145
|
+
|
|
133
146
|
// Re-create the speech recognizer when locales change
|
|
134
147
|
if self.speechRecognizer == nil || currentLocale != options.lang {
|
|
135
148
|
guard let locale = resolveLocale(localeIdentifier: options.lang) else {
|
|
@@ -182,6 +195,9 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
182
195
|
} else {
|
|
183
196
|
self?.sendEvent("audioend", ["uri": nil])
|
|
184
197
|
}
|
|
198
|
+
},
|
|
199
|
+
volumeChangeHandler: { [weak self] value in
|
|
200
|
+
self?.sendEvent("volumechange", ["value": value])
|
|
185
201
|
}
|
|
186
202
|
)
|
|
187
203
|
} catch {
|
|
@@ -358,12 +374,14 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
358
374
|
|
|
359
375
|
func sendErrorAndStop(error: String, message: String) {
|
|
360
376
|
hasSeenFinalResult = false
|
|
377
|
+
previousResult = nil
|
|
361
378
|
sendEvent("error", ["error": error, "message": message])
|
|
362
379
|
sendEvent("end")
|
|
363
380
|
}
|
|
364
381
|
|
|
365
382
|
func handleEnd() {
|
|
366
383
|
hasSeenFinalResult = false
|
|
384
|
+
previousResult = nil
|
|
367
385
|
sendEvent("end")
|
|
368
386
|
}
|
|
369
387
|
|
|
@@ -422,11 +440,21 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
422
440
|
}
|
|
423
441
|
|
|
424
442
|
if isFinal && results.isEmpty {
|
|
425
|
-
//
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
443
|
+
// Hack for iOS 18 to avoid sending a "nomatch" event after the final-final result
|
|
444
|
+
var previousResultWasFinal = false
|
|
445
|
+
var previousResultHadTranscriptions = false
|
|
446
|
+
if #available(iOS 18.0, *), let previousResult = previousResult {
|
|
447
|
+
previousResultWasFinal = previousResult.speechRecognitionMetadata?.speechDuration ?? 0 > 0
|
|
448
|
+
previousResultHadTranscriptions = !previousResult.transcriptions.isEmpty
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
if !previousResultWasFinal || !previousResultHadTranscriptions {
|
|
452
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition/nomatch_event
|
|
453
|
+
// The nomatch event of the Web Speech API is fired
|
|
454
|
+
// when the speech recognition service returns a final result with no significant recognition.
|
|
455
|
+
sendEvent("nomatch")
|
|
456
|
+
return
|
|
457
|
+
}
|
|
430
458
|
}
|
|
431
459
|
|
|
432
460
|
sendEvent(
|
|
@@ -436,6 +464,8 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
436
464
|
"results": results.map { $0.toDictionary() },
|
|
437
465
|
]
|
|
438
466
|
)
|
|
467
|
+
|
|
468
|
+
previousResult = result
|
|
439
469
|
}
|
|
440
470
|
|
|
441
471
|
func handleRecognitionError(_ error: Error) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import AVFoundation
|
|
2
|
+
import Accelerate
|
|
2
3
|
import Foundation
|
|
3
4
|
import Speech
|
|
4
5
|
|
|
@@ -24,7 +25,6 @@ enum RecognizerError: Error {
|
|
|
24
25
|
}
|
|
25
26
|
|
|
26
27
|
actor ExpoSpeechRecognizer: ObservableObject {
|
|
27
|
-
|
|
28
28
|
private var options: SpeechRecognitionOptions?
|
|
29
29
|
private var audioEngine: AVAudioEngine?
|
|
30
30
|
private var request: SFSpeechRecognitionRequest?
|
|
@@ -41,6 +41,7 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
41
41
|
|
|
42
42
|
@MainActor var endHandler: (() -> Void)?
|
|
43
43
|
@MainActor var audioEndHandler: ((String?) -> Void)?
|
|
44
|
+
@MainActor var volumeChangeHandler: ((Float) -> Void)?
|
|
44
45
|
|
|
45
46
|
/// Initializes a new speech recognizer. If this is the first time you've used the class, it
|
|
46
47
|
/// requests access to the speech recognizer and the microphone.
|
|
@@ -120,6 +121,7 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
120
121
|
return recognizer?.locale.identifier
|
|
121
122
|
}
|
|
122
123
|
|
|
124
|
+
// Update the start method signature to include volumeChangeHandler
|
|
123
125
|
@MainActor func start(
|
|
124
126
|
options: SpeechRecognitionOptions,
|
|
125
127
|
resultHandler: @escaping (SFSpeechRecognitionResult) -> Void,
|
|
@@ -128,10 +130,12 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
128
130
|
startHandler: @escaping (() -> Void),
|
|
129
131
|
speechStartHandler: @escaping (() -> Void),
|
|
130
132
|
audioStartHandler: @escaping (String?) -> Void,
|
|
131
|
-
audioEndHandler: @escaping (String?) -> Void
|
|
133
|
+
audioEndHandler: @escaping (String?) -> Void,
|
|
134
|
+
volumeChangeHandler: @escaping (Float) -> Void
|
|
132
135
|
) {
|
|
133
136
|
self.endHandler = endHandler
|
|
134
137
|
self.audioEndHandler = audioEndHandler
|
|
138
|
+
self.volumeChangeHandler = volumeChangeHandler
|
|
135
139
|
Task {
|
|
136
140
|
await startRecognizer(
|
|
137
141
|
options: options,
|
|
@@ -282,12 +286,17 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
282
286
|
mixerNode: mixerNode,
|
|
283
287
|
options: options,
|
|
284
288
|
request: request,
|
|
285
|
-
audioFileRef: self.audioFileRef
|
|
289
|
+
audioFileRef: self.audioFileRef,
|
|
290
|
+
volumeChangeHandler: { volume in
|
|
291
|
+
Task { @MainActor in
|
|
292
|
+
self.volumeChangeHandler?(volume)
|
|
293
|
+
}
|
|
294
|
+
}
|
|
286
295
|
)
|
|
287
296
|
}
|
|
288
297
|
|
|
289
|
-
//
|
|
290
|
-
let
|
|
298
|
+
// Run timers on non-continuous mode, as long as the audio source is the mic
|
|
299
|
+
let shouldRunTimers = !options.continuous && !isSourcedFromFile
|
|
291
300
|
let audioEngine = self.audioEngine
|
|
292
301
|
|
|
293
302
|
self.task = recognizer.recognitionTask(
|
|
@@ -300,18 +309,20 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
300
309
|
}
|
|
301
310
|
}
|
|
302
311
|
|
|
303
|
-
//
|
|
312
|
+
// Handle the result
|
|
304
313
|
self?.recognitionHandler(
|
|
305
314
|
audioEngine: audioEngine,
|
|
306
315
|
result: result,
|
|
307
316
|
error: error,
|
|
308
317
|
resultHandler: resultHandler,
|
|
309
318
|
errorHandler: errorHandler,
|
|
310
|
-
continuous: continuous
|
|
319
|
+
continuous: options.continuous,
|
|
320
|
+
shouldRunTimers: shouldRunTimers,
|
|
321
|
+
canEmitInterimResults: options.interimResults
|
|
311
322
|
)
|
|
312
323
|
})
|
|
313
324
|
|
|
314
|
-
if
|
|
325
|
+
if shouldRunTimers {
|
|
315
326
|
invalidateAndScheduleTimer()
|
|
316
327
|
}
|
|
317
328
|
|
|
@@ -414,6 +425,11 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
414
425
|
stoppedListening = false
|
|
415
426
|
task?.cancel()
|
|
416
427
|
audioEngine?.stop()
|
|
428
|
+
// map through all the attached nodes
|
|
429
|
+
// and remove the tap
|
|
430
|
+
audioEngine?.attachedNodes.forEach(
|
|
431
|
+
{ $0.removeTap(onBus: 0) }
|
|
432
|
+
)
|
|
417
433
|
audioEngine?.inputNode.removeTap(onBus: 0)
|
|
418
434
|
audioEngine?.inputNode.reset()
|
|
419
435
|
audioEngine?.reset()
|
|
@@ -449,7 +465,10 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
449
465
|
request = SFSpeechAudioBufferRecognitionRequest()
|
|
450
466
|
}
|
|
451
467
|
|
|
452
|
-
|
|
468
|
+
// We also force-enable partial results on non-continuous mode,
|
|
469
|
+
// which will allow us to re-schedule timers when text is detected
|
|
470
|
+
// These won't get emitted to the user, however
|
|
471
|
+
request.shouldReportPartialResults = options.interimResults || !options.continuous
|
|
453
472
|
|
|
454
473
|
if recognizer.supportsOnDeviceRecognition {
|
|
455
474
|
request.requiresOnDeviceRecognition = options.requiresOnDeviceRecognition
|
|
@@ -510,7 +529,8 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
510
529
|
mixerNode: AVAudioMixerNode,
|
|
511
530
|
options: SpeechRecognitionOptions,
|
|
512
531
|
request: SFSpeechRecognitionRequest,
|
|
513
|
-
audioFileRef: ExtAudioFileRef
|
|
532
|
+
audioFileRef: ExtAudioFileRef?,
|
|
533
|
+
volumeChangeHandler: ((Float) -> Void)?
|
|
514
534
|
) throws {
|
|
515
535
|
guard let audioBufferRequest = request as? SFSpeechAudioBufferRecognitionRequest else {
|
|
516
536
|
throw RecognizerError.invalidAudioSource
|
|
@@ -559,10 +579,77 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
559
579
|
}
|
|
560
580
|
}
|
|
561
581
|
|
|
582
|
+
// Install separate tap with a longer buffer size to listen for volume changes
|
|
583
|
+
if options.volumeChangeEventOptions?.enabled == true {
|
|
584
|
+
let desiredDuration: TimeInterval =
|
|
585
|
+
TimeInterval(options.volumeChangeEventOptions?.intervalMillis ?? 100) / 1000.0
|
|
586
|
+
let bufferSize = AVAudioFrameCount(audioFormat.sampleRate * desiredDuration)
|
|
587
|
+
|
|
588
|
+
let volumeMixerNode = AVAudioMixerNode()
|
|
589
|
+
audioEngine.attach(volumeMixerNode)
|
|
590
|
+
audioEngine.connect(mixerNode, to: volumeMixerNode, format: audioFormat)
|
|
591
|
+
|
|
592
|
+
volumeMixerNode.installTap(
|
|
593
|
+
onBus: 0,
|
|
594
|
+
bufferSize: bufferSize,
|
|
595
|
+
format: audioFormat
|
|
596
|
+
) { buffer, when in
|
|
597
|
+
guard let power = Self.calculatePower(buffer: buffer) else { return }
|
|
598
|
+
|
|
599
|
+
let minDb: Float = -60.0
|
|
600
|
+
let maxDb: Float = 0.0
|
|
601
|
+
let normalized: Float = (power - minDb) / (maxDb - minDb) // Normalized to 0.0 - 1.0
|
|
602
|
+
let clampedNormalized = min(max(normalized, 0.0), 1.0)
|
|
603
|
+
|
|
604
|
+
let scaledValue = clampedNormalized * (10 - (-2)) + (-2) // Scaled to -2 - 10
|
|
605
|
+
|
|
606
|
+
// Send the volume change event
|
|
607
|
+
volumeChangeHandler?(scaledValue)
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
562
611
|
audioEngine.prepare()
|
|
563
612
|
try audioEngine.start()
|
|
564
613
|
}
|
|
565
614
|
|
|
615
|
+
private static func calculatePower(buffer: AVAudioPCMBuffer) -> Float? {
|
|
616
|
+
// let channelCount = Int(buffer.format.channelCount)
|
|
617
|
+
let length = vDSP_Length(buffer.frameLength)
|
|
618
|
+
let channel = 0
|
|
619
|
+
|
|
620
|
+
if let floatData = buffer.floatChannelData {
|
|
621
|
+
return calculatePowers(data: floatData[channel], strideFrames: buffer.stride, length: length)
|
|
622
|
+
} else if let int16Data = buffer.int16ChannelData {
|
|
623
|
+
// Convert the data from int16 to float values before calculating the power values.
|
|
624
|
+
var floatChannelData: [Float] = Array(repeating: Float(0.0), count: Int(buffer.frameLength))
|
|
625
|
+
vDSP_vflt16(int16Data[channel], buffer.stride, &floatChannelData, buffer.stride, length)
|
|
626
|
+
var scalar = Float(INT16_MAX)
|
|
627
|
+
vDSP_vsdiv(floatChannelData, buffer.stride, &scalar, &floatChannelData, buffer.stride, length)
|
|
628
|
+
return calculatePowers(data: floatChannelData, strideFrames: buffer.stride, length: length)
|
|
629
|
+
} else if let int32Data = buffer.int32ChannelData {
|
|
630
|
+
// Convert the data from int32 to float values before calculating the power values.
|
|
631
|
+
var floatChannelData: [Float] = Array(repeating: Float(0.0), count: Int(buffer.frameLength))
|
|
632
|
+
vDSP_vflt32(int32Data[channel], buffer.stride, &floatChannelData, buffer.stride, length)
|
|
633
|
+
var scalar = Float(INT32_MAX)
|
|
634
|
+
vDSP_vsdiv(floatChannelData, buffer.stride, &scalar, &floatChannelData, buffer.stride, length)
|
|
635
|
+
return calculatePowers(data: floatChannelData, strideFrames: buffer.stride, length: length)
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
return nil
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
private static func calculatePowers(
|
|
642
|
+
data: UnsafePointer<Float>, strideFrames: Int, length: vDSP_Length
|
|
643
|
+
) -> Float? {
|
|
644
|
+
let kMinLevel: Float = 1e-7 // -160 dB
|
|
645
|
+
var max: Float = 0.0
|
|
646
|
+
vDSP_maxv(data, strideFrames, &max, length)
|
|
647
|
+
if max < kMinLevel {
|
|
648
|
+
max = kMinLevel
|
|
649
|
+
}
|
|
650
|
+
return 20.0 * log10(max)
|
|
651
|
+
}
|
|
652
|
+
|
|
566
653
|
/// Downsamples the audio buffer to a file ref
|
|
567
654
|
private static func downsampleToFile(
|
|
568
655
|
buffer: AVAudioPCMBuffer,
|
|
@@ -613,12 +700,25 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
613
700
|
error: Error?,
|
|
614
701
|
resultHandler: @escaping (SFSpeechRecognitionResult) -> Void,
|
|
615
702
|
errorHandler: @escaping (Error) -> Void,
|
|
616
|
-
continuous: Bool
|
|
703
|
+
continuous: Bool,
|
|
704
|
+
shouldRunTimers: Bool,
|
|
705
|
+
canEmitInterimResults: Bool
|
|
617
706
|
) {
|
|
707
|
+
// When a final result is returned, we should expect the task to be idle or stopping
|
|
618
708
|
let receivedFinalResult = result?.isFinal ?? false
|
|
619
709
|
let receivedError = error != nil
|
|
620
710
|
|
|
621
|
-
|
|
711
|
+
// Hack for iOS 18 to detect final results
|
|
712
|
+
// See: https://forums.developer.apple.com/forums/thread/762952 for more info
|
|
713
|
+
// This can be emitted multiple times during a continuous session, unlike `result.isFinal` which is only emitted once
|
|
714
|
+
var receivedFinalLikeResult: Bool = receivedFinalResult
|
|
715
|
+
if #available(iOS 18.0, *), !receivedFinalLikeResult {
|
|
716
|
+
receivedFinalLikeResult = result?.speechRecognitionMetadata?.speechDuration ?? 0 > 0
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
let shouldEmitResult = receivedFinalResult || canEmitInterimResults || receivedFinalLikeResult
|
|
720
|
+
|
|
721
|
+
if let result: SFSpeechRecognitionResult, shouldEmitResult {
|
|
622
722
|
Task { @MainActor in
|
|
623
723
|
let taskState = await task?.state
|
|
624
724
|
// Make sure the task is running before emitting the result
|
|
@@ -638,15 +738,16 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
638
738
|
}
|
|
639
739
|
}
|
|
640
740
|
|
|
641
|
-
if
|
|
741
|
+
if (receivedFinalLikeResult && !continuous) || receivedError || receivedFinalResult {
|
|
642
742
|
Task { @MainActor in
|
|
643
743
|
await reset()
|
|
644
744
|
}
|
|
745
|
+
return
|
|
645
746
|
}
|
|
646
747
|
|
|
647
748
|
// Non-continuous speech recognition
|
|
648
749
|
// Stop the speech recognizer if the timer fires after not receiving a result for 3 seconds
|
|
649
|
-
if
|
|
750
|
+
if shouldRunTimers && !receivedError {
|
|
650
751
|
invalidateAndScheduleTimer()
|
|
651
752
|
}
|
|
652
753
|
}
|
|
@@ -34,6 +34,17 @@ struct SpeechRecognitionOptions: Record {
|
|
|
34
34
|
|
|
35
35
|
@Field
|
|
36
36
|
var iosCategory: SetCategoryOptions? = nil
|
|
37
|
+
|
|
38
|
+
@Field
|
|
39
|
+
var volumeChangeEventOptions: VolumeChangeEventOptions? = nil
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
struct VolumeChangeEventOptions: Record {
|
|
43
|
+
@Field
|
|
44
|
+
var enabled: Bool? = false
|
|
45
|
+
|
|
46
|
+
@Field
|
|
47
|
+
var intervalMillis: Int? = nil
|
|
37
48
|
}
|
|
38
49
|
|
|
39
50
|
enum IOSTaskHint: String, Enumerable {
|
package/package.json
CHANGED
|
@@ -127,6 +127,14 @@ export type ExpoSpeechRecognitionNativeEventMap = {
|
|
|
127
127
|
end: null;
|
|
128
128
|
soundstart: null;
|
|
129
129
|
soundend: null;
|
|
130
|
+
volumechange: {
|
|
131
|
+
/**
|
|
132
|
+
* A float value between -2 and 10 indicating the volume of the input audio
|
|
133
|
+
*
|
|
134
|
+
* Consider anything below 0 to be inaudible
|
|
135
|
+
*/
|
|
136
|
+
value: number;
|
|
137
|
+
};
|
|
130
138
|
};
|
|
131
139
|
|
|
132
140
|
export type ExpoSpeechRecognitionOptions = {
|
|
@@ -149,7 +157,10 @@ export type ExpoSpeechRecognitionOptions = {
|
|
|
149
157
|
*
|
|
150
158
|
* Not supported on Android 12 and below.
|
|
151
159
|
*
|
|
152
|
-
* If false
|
|
160
|
+
* If false, the behaviors are the following:
|
|
161
|
+
*
|
|
162
|
+
* - on iOS 17-, recognition will run until no speech is detected for 3 seconds.
|
|
163
|
+
* - on iOS 18+ and Android, recognition will run until a result with `isFinal: true` is received.
|
|
153
164
|
*/
|
|
154
165
|
continuous?: boolean;
|
|
155
166
|
/** [Default: false] Prevent device from sending audio over the network. Only enabled if the device supports it.
|
|
@@ -231,6 +242,26 @@ export type ExpoSpeechRecognitionOptions = {
|
|
|
231
242
|
* Docs: https://developer.apple.com/documentation/avfaudio/avaudiosession/category
|
|
232
243
|
*/
|
|
233
244
|
iosCategory?: SetCategoryOptions;
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Settings for volume change events.
|
|
248
|
+
*/
|
|
249
|
+
volumeChangeEventOptions?: {
|
|
250
|
+
/**
|
|
251
|
+
* Whether to emit volume change events.
|
|
252
|
+
*
|
|
253
|
+
* Default: false
|
|
254
|
+
*/
|
|
255
|
+
enabled?: boolean;
|
|
256
|
+
/**
|
|
257
|
+
* Specifies the interval (in milliseconds) to emit `volumechange` events.
|
|
258
|
+
*
|
|
259
|
+
* Default: 100ms on iOS
|
|
260
|
+
*
|
|
261
|
+
* Increasing this value will improve performance
|
|
262
|
+
*/
|
|
263
|
+
intervalMillis?: number;
|
|
264
|
+
};
|
|
234
265
|
};
|
|
235
266
|
|
|
236
267
|
export type IOSTaskHintValue = (typeof TaskHintIOS)[keyof typeof TaskHintIOS];
|