expo-speech-recognition 0.2.24 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +94 -69
- package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionModule.kt +44 -0
- package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechService.kt +37 -3
- package/build/ExpoSpeechRecognitionModule.types.d.ts +59 -3
- package/build/ExpoSpeechRecognitionModule.types.d.ts.map +1 -1
- package/build/ExpoSpeechRecognitionModule.types.js.map +1 -1
- package/build/ExpoSpeechRecognitionModule.web.d.ts.map +1 -1
- package/build/ExpoSpeechRecognitionModule.web.js +85 -14
- package/build/ExpoSpeechRecognitionModule.web.js.map +1 -1
- package/build/ExpoWebSpeechRecognition.d.ts.map +1 -1
- package/build/ExpoWebSpeechRecognition.js +0 -2
- package/build/ExpoWebSpeechRecognition.js.map +1 -1
- package/build/index.d.ts +2 -3
- package/build/index.d.ts.map +1 -1
- package/build/index.js +3 -3
- package/build/index.js.map +1 -1
- package/ios/ExpoSpeechRecognitionModule.swift +57 -3
- package/ios/ExpoSpeechRecognizer.swift +182 -112
- package/ios/MicrophoneRequester.swift +33 -0
- package/ios/SpeechRecognizerRequester.swift +34 -0
- package/package.json +6 -1
- package/src/ExpoSpeechRecognitionModule.types.ts +60 -3
- package/src/ExpoSpeechRecognitionModule.web.ts +102 -16
- package/src/ExpoWebSpeechRecognition.ts +1 -2
- package/src/index.ts +4 -14
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAG5E,oCAAoC;AACpC,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,4BAA4B,CAAC;AAEpC,gBAAgB;AAChB,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAE5E,QAAQ;AACR,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAExE,YAAY;AACZ,OAAO,EACL,sBAAsB,EACtB,6BAA6B,EAC7B,kBAAkB,EAClB,kCAAkC,EAClC,oCAAoC,EACpC,oBAAoB,EACpB,WAAW,GACZ,MAAM,aAAa,CAAC;AAErB,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,OAEnC,EAAE,EAAE,CAAC,2BAA2B,CAAC,mBAAmB,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC;AAErE,MAAM,CAAC,MAAM,4BAA4B,GACvC,2BAA2B,CAAC,4BAA4B,CAAC;AAE3D,MAAM,CAAC,MAAM,2BAA2B,GACtC,2BAA2B,CAAC,2BAA2B,CAAC;AAE1D,MAAM,CAAC,MAAM,iBAAiB,GAAG,2BAA2B,CAAC,iBAAiB,CAAC;AAE/E,MAAM,CAAC,MAAM,cAAc,GAAG,2BAA2B,CAAC,cAAc,CAAC;AAEzE,MAAM,CAAC,MAAM,oCAAoC,GAC/C,2BAA2B,CAAC,oCAAoC,CAAC;AAEnE,MAAM,CAAC,MAAM,wBAAwB,GACnC,2BAA2B,CAAC,wBAAwB,CAAC;AAEvD,MAAM,CAAC,MAAM,kCAAkC,GAC7C,2BAA2B,CAAC,kCAAkC,CAAC;AAEjE,MAAM,CAAC,MAAM,sBAAsB,GACjC,2BAA2B,CAAC,sBAAsB,CAAC;AAErD,MAAM,CAAC,MAAM,4BAA4B,GACvC,2BAA2B,CAAC,4BAA4B,CAAC;AAE3D,MAAM,CAAC,MAAM,mBAAmB,GAC9B,2BAA2B,CAAC,mBAAmB,CAAC;AAElD,MAAM,CAAC,MAAM,4BAA4B,GACvC,2BAA2B,CAAC,WAAW,CAAC","sourcesContent":["import { ExpoSpeechRecognitionModule } from \"./ExpoSpeechRecognitionModule\";\nimport type { ExpoSpeechRecognitionNativeEventMap } from \"./ExpoSpeechRecognitionModule.types\";\n\n// Export the SpeechRecognition APIs\nexport {\n ExpoWebSpeechRecognition,\n ExpoWebSpeechGrammar,\n ExpoWebSpeechGrammarList,\n} from \"./ExpoWebSpeechRecognition\";\n\n// Native module\nexport { ExpoSpeechRecognitionModule } from \"./ExpoSpeechRecognitionModule\";\n\n// Hooks\nexport { useSpeechRecognitionEvent } from \"./useSpeechRecognitionEvent\";\n\n// Constants\nexport {\n AVAudioSessionCategory,\n AVAudioSessionCategoryOptions,\n AVAudioSessionMode,\n RecognizerIntentExtraLanguageModel,\n RecognizerIntentEnableLanguageSwitch,\n AudioEncodingAndroid,\n TaskHintIOS,\n} from \"./constants\";\n\nexport const getSupportedLocales = (options?: {\n androidRecognitionServicePackage?: string;\n}) => ExpoSpeechRecognitionModule.getSupportedLocales(options ?? {});\n\nexport const getSpeechRecognitionServices =\n ExpoSpeechRecognitionModule.getSpeechRecognitionServices;\n\nexport const supportsOnDeviceRecognition =\n ExpoSpeechRecognitionModule.supportsOnDeviceRecognition;\n\nexport const supportsRecording = ExpoSpeechRecognitionModule.supportsRecording;\n\nexport const setCategoryIOS = ExpoSpeechRecognitionModule.setCategoryIOS;\n\nexport const getAudioSessionCategoryAndOptionsIOS =\n ExpoSpeechRecognitionModule.getAudioSessionCategoryAndOptionsIOS;\n\nexport const setAudioSessionActiveIOS =\n ExpoSpeechRecognitionModule.setAudioSessionActiveIOS;\n\nexport const androidTriggerOfflineModelDownload =\n ExpoSpeechRecognitionModule.androidTriggerOfflineModelDownload;\n\nexport const isRecognitionAvailable =\n ExpoSpeechRecognitionModule.isRecognitionAvailable;\n\nexport const getDefaultRecognitionService =\n ExpoSpeechRecognitionModule.getDefaultRecognitionService;\n\nexport const getAssistantService =\n ExpoSpeechRecognitionModule.getAssistantService;\n\nexport const addSpeechRecognitionListener =\n ExpoSpeechRecognitionModule.addListener;\n\nexport {\n type ExpoSpeechRecognitionOptions,\n type AndroidIntentOptions,\n type ExpoSpeechRecognitionNativeEventMap,\n type AVAudioSessionCategoryOptionsValue,\n type AVAudioSessionModeValue,\n type AVAudioSessionCategoryValue,\n type AudioEncodingAndroidValue,\n type AudioSourceOptions,\n type RecordingOptions,\n type IOSTaskHintValue,\n type SetCategoryOptions,\n type ExpoSpeechRecognitionErrorCode,\n type ExpoSpeechRecognitionErrorEvent,\n type ExpoSpeechRecognitionResultEvent,\n type ExpoSpeechRecognitionResult,\n type ExpoSpeechRecognitionResultSegment,\n} from \"./ExpoSpeechRecognitionModule.types\";\n"]}
|
|
@@ -92,8 +92,8 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
92
92
|
// Fired when the speech recognition service has begun listening to incoming audio with
|
|
93
93
|
// intent to recognize grammars associated with the current SpeechRecognition
|
|
94
94
|
"start",
|
|
95
|
-
// Called when
|
|
96
|
-
"
|
|
95
|
+
// Called when the language detection (and switching) results are available.
|
|
96
|
+
"languagedetection",
|
|
97
97
|
// Fired when the input volume changes
|
|
98
98
|
"volumechange"
|
|
99
99
|
)
|
|
@@ -102,7 +102,11 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
102
102
|
guard let permissionsManager = appContext?.permissions else {
|
|
103
103
|
return
|
|
104
104
|
}
|
|
105
|
-
permissionsManager.register([
|
|
105
|
+
permissionsManager.register([
|
|
106
|
+
EXSpeechRecognitionPermissionRequester(),
|
|
107
|
+
MicrophoneRequester(),
|
|
108
|
+
SpeechRecognizerRequester()
|
|
109
|
+
])
|
|
106
110
|
}
|
|
107
111
|
|
|
108
112
|
AsyncFunction("requestPermissionsAsync") { (promise: Promise) in
|
|
@@ -127,6 +131,38 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
127
131
|
)
|
|
128
132
|
}
|
|
129
133
|
|
|
134
|
+
AsyncFunction("getMicrophonePermissionsAsync") { (promise: Promise) in
|
|
135
|
+
appContext?.permissions?.getPermissionUsingRequesterClass(
|
|
136
|
+
MicrophoneRequester.self,
|
|
137
|
+
resolve: promise.resolver,
|
|
138
|
+
reject: promise.legacyRejecter
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
AsyncFunction("requestMicrophonePermissionsAsync") { (promise: Promise) in
|
|
143
|
+
appContext?.permissions?.askForPermission(
|
|
144
|
+
usingRequesterClass: MicrophoneRequester.self,
|
|
145
|
+
resolve: promise.resolver,
|
|
146
|
+
reject: promise.legacyRejecter
|
|
147
|
+
)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
AsyncFunction("getSpeechRecognizerPermissionsAsync") { (promise: Promise) in
|
|
151
|
+
appContext?.permissions?.getPermissionUsingRequesterClass(
|
|
152
|
+
SpeechRecognizerRequester.self,
|
|
153
|
+
resolve: promise.resolver,
|
|
154
|
+
reject: promise.legacyRejecter
|
|
155
|
+
)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
AsyncFunction("requestSpeechRecognizerPermissionsAsync") { (promise: Promise) in
|
|
159
|
+
appContext?.permissions?.askForPermission(
|
|
160
|
+
usingRequesterClass: SpeechRecognizerRequester.self,
|
|
161
|
+
resolve: promise.resolver,
|
|
162
|
+
reject: promise.legacyRejecter
|
|
163
|
+
)
|
|
164
|
+
}
|
|
165
|
+
|
|
130
166
|
AsyncFunction("getStateAsync") { (promise: Promise) in
|
|
131
167
|
Task {
|
|
132
168
|
let state = await speechRecognizer?.getState()
|
|
@@ -161,6 +197,24 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
161
197
|
locale: locale
|
|
162
198
|
)
|
|
163
199
|
}
|
|
200
|
+
|
|
201
|
+
if !options.requiresOnDeviceRecognition {
|
|
202
|
+
guard await SFSpeechRecognizer.hasAuthorizationToRecognize() else {
|
|
203
|
+
sendErrorAndStop(
|
|
204
|
+
error: "not-allowed",
|
|
205
|
+
message: RecognizerError.notAuthorizedToRecognize.message
|
|
206
|
+
)
|
|
207
|
+
return
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
guard await AVAudioSession.sharedInstance().hasPermissionToRecord() else {
|
|
212
|
+
sendErrorAndStop(
|
|
213
|
+
error: "not-allowed",
|
|
214
|
+
message: RecognizerError.notPermittedToRecord.message
|
|
215
|
+
)
|
|
216
|
+
return
|
|
217
|
+
}
|
|
164
218
|
|
|
165
219
|
// Start recognition!
|
|
166
220
|
await speechRecognizer?.start(
|
|
@@ -56,14 +56,6 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
56
56
|
guard recognizer != nil else {
|
|
57
57
|
throw RecognizerError.nilRecognizer
|
|
58
58
|
}
|
|
59
|
-
|
|
60
|
-
guard await SFSpeechRecognizer.hasAuthorizationToRecognize() else {
|
|
61
|
-
throw RecognizerError.notAuthorizedToRecognize
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
guard await AVAudioSession.sharedInstance().hasPermissionToRecord() else {
|
|
65
|
-
throw RecognizerError.notPermittedToRecord
|
|
66
|
-
}
|
|
67
59
|
}
|
|
68
60
|
|
|
69
61
|
/// Returns a suitable audio format to use for the speech recognition task and audio file recording.
|
|
@@ -207,6 +199,8 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
207
199
|
// Reset the speech recognizer before starting
|
|
208
200
|
reset(andEmitEnd: false)
|
|
209
201
|
|
|
202
|
+
self.options = options
|
|
203
|
+
self.request = nil
|
|
210
204
|
self.outputFileUrl = nil
|
|
211
205
|
self.speechStartHandler = speechStartHandler
|
|
212
206
|
|
|
@@ -222,118 +216,166 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
222
216
|
recognizer: recognizer
|
|
223
217
|
)
|
|
224
218
|
self.request = request
|
|
225
|
-
|
|
226
|
-
// Check if options.audioSource is set, if it is, then it is sourced from a file
|
|
227
219
|
let isSourcedFromFile = options.audioSource?.uri != nil
|
|
228
220
|
|
|
229
|
-
if
|
|
230
|
-
|
|
231
|
-
|
|
221
|
+
// Check if options.audioSource is set, if it is, then it is sourced from a file
|
|
222
|
+
if let audioSource = options.audioSource?.uri {
|
|
223
|
+
try prepareFileRecognition(request: request, url: URL(string: audioSource)!)
|
|
232
224
|
} else {
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
self.audioEngine = AVAudioEngine()
|
|
225
|
+
try prepareMicrophoneRecognition(request: request, options: options)
|
|
226
|
+
}
|
|
237
227
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
228
|
+
startRecognitionTask(
|
|
229
|
+
with: request,
|
|
230
|
+
recognizer: recognizer,
|
|
231
|
+
resultHandler: resultHandler,
|
|
232
|
+
errorHandler: errorHandler,
|
|
233
|
+
continuous: options.continuous,
|
|
234
|
+
canEmitInterimResults: options.interimResults,
|
|
235
|
+
isSourcedFromFile: isSourcedFromFile
|
|
236
|
+
)
|
|
242
237
|
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
// `required condition is false: format.sampleRate == hwFormat.sampleRate`
|
|
246
|
-
// (under the hood it calls `AVAudioEngineImpl::UpdateInputNode` -> `AVAudioNode setOutputFormat:forBus:0`)
|
|
247
|
-
let audioFormat = Self.getAudioFormat(forEngine: audioEngine)
|
|
238
|
+
// Emit the "start" event to indicate that speech recognition has started
|
|
239
|
+
startHandler()
|
|
248
240
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
241
|
+
// If user has opted in to recording, emit an "audiostart" event with the path
|
|
242
|
+
audioStartHandler(outputFileUrl?.path)
|
|
243
|
+
} catch {
|
|
244
|
+
errorHandler(error)
|
|
245
|
+
reset(andEmitEnd: true)
|
|
246
|
+
}
|
|
247
|
+
}
|
|
256
248
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
else {
|
|
269
|
-
print(
|
|
270
|
-
"expo-speech-recognition: ERROR - Failed to create AVAudioFormat from given sample rate"
|
|
271
|
-
)
|
|
272
|
-
throw RecognizerError.invalidAudioSource
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
let outputUrl = prepareFileWriter(
|
|
276
|
-
outputDirectory: options.recordingOptions?.outputDirectory,
|
|
277
|
-
outputFileName: options.recordingOptions?.outputFileName,
|
|
278
|
-
audioFormat: fileAudioFormat
|
|
279
|
-
)
|
|
280
|
-
self.outputFileUrl = outputUrl
|
|
281
|
-
}
|
|
249
|
+
private func startRecognitionTask(
|
|
250
|
+
with request: SFSpeechRecognitionRequest,
|
|
251
|
+
recognizer: SFSpeechRecognizer,
|
|
252
|
+
resultHandler: @escaping (SFSpeechRecognitionResult) -> Void,
|
|
253
|
+
errorHandler: @escaping (Error) -> Void,
|
|
254
|
+
continuous: Bool,
|
|
255
|
+
canEmitInterimResults: Bool,
|
|
256
|
+
isSourcedFromFile: Bool
|
|
257
|
+
) {
|
|
258
|
+
let audioEngine = self.audioEngine
|
|
259
|
+
let shouldRunTimers = !continuous && !isSourcedFromFile
|
|
282
260
|
|
|
283
|
-
|
|
284
|
-
|
|
261
|
+
self.task = recognizer.recognitionTask(
|
|
262
|
+
with: request,
|
|
263
|
+
resultHandler: { [weak self] result, error in
|
|
264
|
+
self?.recognitionHandler(
|
|
285
265
|
audioEngine: audioEngine,
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
}
|
|
266
|
+
result: result,
|
|
267
|
+
error: error,
|
|
268
|
+
resultHandler: resultHandler,
|
|
269
|
+
errorHandler: errorHandler,
|
|
270
|
+
continuous: continuous,
|
|
271
|
+
shouldRunTimers: shouldRunTimers,
|
|
272
|
+
canEmitInterimResults: canEmitInterimResults,
|
|
273
|
+
isSourcedFromFile: isSourcedFromFile
|
|
295
274
|
)
|
|
296
275
|
}
|
|
276
|
+
)
|
|
277
|
+
}
|
|
297
278
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
let audioEngine = self.audioEngine
|
|
279
|
+
private func prepareFileRecognition(request: SFSpeechRecognitionRequest, url: URL) throws {
|
|
280
|
+
self.audioEngine = nil
|
|
301
281
|
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
282
|
+
guard let request = self.request as? SFSpeechAudioBufferRecognitionRequest else {
|
|
283
|
+
throw RecognizerError.invalidAudioSource
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
let chunkDelayMillis: Int
|
|
287
|
+
if let options = self.options, let specifiedDelay = options.audioSource?.chunkDelayMillis {
|
|
288
|
+
chunkDelayMillis = specifiedDelay
|
|
289
|
+
} else if self.options?.requiresOnDeviceRecognition == true {
|
|
290
|
+
chunkDelayMillis = 15 // On-device recognition
|
|
291
|
+
} else {
|
|
292
|
+
chunkDelayMillis = 50 // Network-based recognition
|
|
293
|
+
}
|
|
294
|
+
let chunkDelayNs = UInt64(chunkDelayMillis) * 1_000_000
|
|
295
|
+
// var playbackBuffers = [AVAudioPCMBuffer]()
|
|
296
|
+
|
|
297
|
+
Task.detached(priority: .userInitiated) {
|
|
298
|
+
do {
|
|
299
|
+
let file = try AVAudioFile(forReading: url)
|
|
300
|
+
let bufferCapacity: AVAudioFrameCount = 4096
|
|
301
|
+
let inputBuffer = AVAudioPCMBuffer(
|
|
302
|
+
pcmFormat: file.processingFormat, frameCapacity: bufferCapacity
|
|
303
|
+
)!
|
|
304
|
+
|
|
305
|
+
while file.framePosition < file.length {
|
|
306
|
+
let framesToRead = min(
|
|
307
|
+
bufferCapacity, AVAudioFrameCount(file.length - file.framePosition)
|
|
322
308
|
)
|
|
323
|
-
|
|
309
|
+
try file.read(into: inputBuffer, frameCount: framesToRead)
|
|
310
|
+
request.append(inputBuffer)
|
|
311
|
+
// playbackBuffers.append(inputBuffer.copy() as! AVAudioPCMBuffer)
|
|
312
|
+
try await Task.sleep(nanoseconds: chunkDelayNs)
|
|
313
|
+
}
|
|
324
314
|
|
|
325
|
-
|
|
326
|
-
|
|
315
|
+
print("[expo-speech-recognition]: Audio streaming ended")
|
|
316
|
+
request.endAudio()
|
|
317
|
+
// await self.playBack(playbackBuffers: playbackBuffers)
|
|
318
|
+
} catch {
|
|
319
|
+
print("[expo-speech-recognition]: Error feeding audio file: \(error)")
|
|
320
|
+
request.endAudio()
|
|
327
321
|
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
328
324
|
|
|
329
|
-
|
|
330
|
-
|
|
325
|
+
private func prepareMicrophoneRecognition(
|
|
326
|
+
request: SFSpeechRecognitionRequest,
|
|
327
|
+
options: SpeechRecognitionOptions
|
|
328
|
+
) throws {
|
|
329
|
+
try Self.setupAudioSession(options.iosCategory)
|
|
330
|
+
self.audioEngine = AVAudioEngine()
|
|
331
331
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
332
|
+
guard let audioEngine = self.audioEngine else {
|
|
333
|
+
print("expo-speech-recognition: ERROR - Failed to create AVAudioEngine")
|
|
334
|
+
throw RecognizerError.invalidAudioSource
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
let inputNode = audioEngine.inputNode
|
|
338
|
+
let audioFormat = Self.getAudioFormat(forEngine: audioEngine)
|
|
339
|
+
|
|
340
|
+
guard !Self.audioInputIsBusy(audioFormat) else {
|
|
341
|
+
print("expo-speech-recognition: ERROR - input is busy \(audioFormat)")
|
|
342
|
+
throw RecognizerError.audioInputBusy
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
let mixerNode = AVAudioMixerNode()
|
|
346
|
+
audioEngine.attach(mixerNode)
|
|
347
|
+
audioEngine.connect(inputNode, to: mixerNode, format: audioFormat)
|
|
348
|
+
|
|
349
|
+
if options.recordingOptions?.persist == true {
|
|
350
|
+
guard let fileAudioFormat = Self.getFileAudioFormat(options: options, engine: audioEngine)
|
|
351
|
+
else {
|
|
352
|
+
print(
|
|
353
|
+
"expo-speech-recognition: ERROR - Failed to create AVAudioFormat from given sample rate")
|
|
354
|
+
throw RecognizerError.invalidAudioSource
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
self.outputFileUrl = prepareFileWriter(
|
|
358
|
+
outputDirectory: options.recordingOptions?.outputDirectory,
|
|
359
|
+
outputFileName: options.recordingOptions?.outputFileName,
|
|
360
|
+
audioFormat: fileAudioFormat
|
|
361
|
+
)
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
try Self.prepareEngine(
|
|
365
|
+
audioEngine: audioEngine,
|
|
366
|
+
mixerNode: mixerNode,
|
|
367
|
+
options: options,
|
|
368
|
+
request: request,
|
|
369
|
+
audioFileRef: self.audioFileRef,
|
|
370
|
+
volumeChangeHandler: { volume in
|
|
371
|
+
Task { @MainActor in
|
|
372
|
+
self.volumeChangeHandler?(volume)
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
if !options.continuous {
|
|
378
|
+
invalidateAndScheduleTimer()
|
|
337
379
|
}
|
|
338
380
|
}
|
|
339
381
|
|
|
@@ -455,15 +497,10 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
455
497
|
}
|
|
456
498
|
|
|
457
499
|
private static func prepareRequest(
|
|
458
|
-
options: SpeechRecognitionOptions,
|
|
500
|
+
options: SpeechRecognitionOptions,
|
|
501
|
+
recognizer: SFSpeechRecognizer
|
|
459
502
|
) -> SFSpeechRecognitionRequest {
|
|
460
|
-
|
|
461
|
-
let request: SFSpeechRecognitionRequest
|
|
462
|
-
if let audioSource = options.audioSource {
|
|
463
|
-
request = SFSpeechURLRecognitionRequest(url: URL(string: audioSource.uri)!)
|
|
464
|
-
} else {
|
|
465
|
-
request = SFSpeechAudioBufferRecognitionRequest()
|
|
466
|
-
}
|
|
503
|
+
let request = SFSpeechAudioBufferRecognitionRequest()
|
|
467
504
|
|
|
468
505
|
// We also force-enable partial results on non-continuous mode,
|
|
469
506
|
// which will allow us to re-schedule timers when text is detected
|
|
@@ -702,7 +739,8 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
702
739
|
errorHandler: @escaping (Error) -> Void,
|
|
703
740
|
continuous: Bool,
|
|
704
741
|
shouldRunTimers: Bool,
|
|
705
|
-
canEmitInterimResults: Bool
|
|
742
|
+
canEmitInterimResults: Bool,
|
|
743
|
+
isSourcedFromFile: Bool
|
|
706
744
|
) {
|
|
707
745
|
// When a final result is returned, we should expect the task to be idle or stopping
|
|
708
746
|
let receivedFinalResult = result?.isFinal ?? false
|
|
@@ -738,7 +776,9 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
738
776
|
}
|
|
739
777
|
}
|
|
740
778
|
|
|
741
|
-
if (receivedFinalLikeResult && !continuous
|
|
779
|
+
if receivedError || (receivedFinalLikeResult && !continuous && !isSourcedFromFile)
|
|
780
|
+
|| receivedFinalResult
|
|
781
|
+
{
|
|
742
782
|
Task { @MainActor in
|
|
743
783
|
await reset()
|
|
744
784
|
}
|
|
@@ -781,6 +821,36 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
781
821
|
}
|
|
782
822
|
}
|
|
783
823
|
}
|
|
824
|
+
|
|
825
|
+
/*
|
|
826
|
+
private var playbackEngine: AVAudioEngine?
|
|
827
|
+
private var playerNode: AVAudioPlayerNode?
|
|
828
|
+
/// Playback audio from an array of AVAudioPCMBuffers
|
|
829
|
+
/// For testing purposes only
|
|
830
|
+
func playBack(playbackBuffers: [AVAudioPCMBuffer]) {
|
|
831
|
+
guard !playbackBuffers.isEmpty else { return }
|
|
832
|
+
|
|
833
|
+
playbackEngine = AVAudioEngine()
|
|
834
|
+
playerNode = AVAudioPlayerNode()
|
|
835
|
+
|
|
836
|
+
guard let playbackEngine = playbackEngine, let playerNode = playerNode else { return }
|
|
837
|
+
|
|
838
|
+
playbackEngine.attach(playerNode)
|
|
839
|
+
let outputFormat = playbackBuffers[0].format
|
|
840
|
+
playbackEngine.connect(playerNode, to: playbackEngine.mainMixerNode, format: outputFormat)
|
|
841
|
+
|
|
842
|
+
for buffer in playbackBuffers {
|
|
843
|
+
playerNode.scheduleBuffer(buffer, completionHandler: nil)
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
do {
|
|
847
|
+
try playbackEngine.start()
|
|
848
|
+
playerNode.play()
|
|
849
|
+
} catch {
|
|
850
|
+
print("Failed to start playback engine: \(error)")
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
*/
|
|
784
854
|
}
|
|
785
855
|
|
|
786
856
|
extension SFSpeechRecognizer {
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import ExpoModulesCore
|
|
2
|
+
|
|
3
|
+
public class MicrophoneRequester: NSObject, EXPermissionsRequester {
|
|
4
|
+
static public func permissionType() -> String {
|
|
5
|
+
return "microphone"
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
public func requestPermissions(
|
|
9
|
+
resolver resolve: @escaping EXPromiseResolveBlock, rejecter reject: EXPromiseRejectBlock
|
|
10
|
+
) {
|
|
11
|
+
AVAudioSession.sharedInstance().requestRecordPermission { authorized in
|
|
12
|
+
resolve(self.getPermissions())
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
public func getPermissions() -> [AnyHashable: Any] {
|
|
17
|
+
var status: EXPermissionStatus
|
|
18
|
+
|
|
19
|
+
let recordPermission = AVAudioSession.sharedInstance().recordPermission
|
|
20
|
+
|
|
21
|
+
if recordPermission == .granted {
|
|
22
|
+
status = EXPermissionStatusGranted
|
|
23
|
+
} else if recordPermission == .denied {
|
|
24
|
+
status = EXPermissionStatusDenied
|
|
25
|
+
} else {
|
|
26
|
+
status = EXPermissionStatusUndetermined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
return [
|
|
30
|
+
"status": status.rawValue
|
|
31
|
+
]
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import ExpoModulesCore
|
|
2
|
+
import Speech
|
|
3
|
+
|
|
4
|
+
public class SpeechRecognizerRequester: NSObject, EXPermissionsRequester {
|
|
5
|
+
static public func permissionType() -> String {
|
|
6
|
+
return "speechRecognizer"
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
public func requestPermissions(
|
|
10
|
+
resolver resolve: @escaping EXPromiseResolveBlock, rejecter reject: EXPromiseRejectBlock
|
|
11
|
+
) {
|
|
12
|
+
SFSpeechRecognizer.requestAuthorization { status in
|
|
13
|
+
resolve(self.getPermissions())
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
public func getPermissions() -> [AnyHashable: Any] {
|
|
18
|
+
var status: EXPermissionStatus
|
|
19
|
+
|
|
20
|
+
let speechPermission = SFSpeechRecognizer.authorizationStatus()
|
|
21
|
+
|
|
22
|
+
if speechPermission == .authorized {
|
|
23
|
+
status = EXPermissionStatusGranted
|
|
24
|
+
} else if speechPermission == .denied {
|
|
25
|
+
status = EXPermissionStatusDenied
|
|
26
|
+
} else {
|
|
27
|
+
status = EXPermissionStatusUndetermined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return [
|
|
31
|
+
"status": status.rawValue
|
|
32
|
+
]
|
|
33
|
+
}
|
|
34
|
+
}
|
package/package.json
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "expo-speech-recognition",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Speech Recognition for React Native Expo projects",
|
|
5
5
|
"main": "build/index.js",
|
|
6
6
|
"types": "build/index.d.ts",
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
7
10
|
"scripts": {
|
|
8
11
|
"build": "expo-module build",
|
|
9
12
|
"clean": "expo-module clean",
|
|
@@ -14,6 +17,7 @@
|
|
|
14
17
|
"expo-module": "expo-module",
|
|
15
18
|
"open:ios": "open -a \"Xcode\" example/ios",
|
|
16
19
|
"open:android": "open -a \"Android Studio\" example/android",
|
|
20
|
+
"release": "npm run prepare && changeset publish",
|
|
17
21
|
"ts:check": "tsc -p . --noEmit"
|
|
18
22
|
},
|
|
19
23
|
"keywords": [
|
|
@@ -32,6 +36,7 @@
|
|
|
32
36
|
"license": "MIT",
|
|
33
37
|
"homepage": "https://github.com/jamsch/expo-speech-recognition#readme",
|
|
34
38
|
"devDependencies": {
|
|
39
|
+
"@changesets/cli": "^2.27.9",
|
|
35
40
|
"@types/dom-speech-recognition": "^0.0.4",
|
|
36
41
|
"@types/react": "^18.3.3",
|
|
37
42
|
"expo-module-scripts": "^3.5.2",
|
|
@@ -88,6 +88,23 @@ export type ExpoSpeechRecognitionErrorEvent = {
|
|
|
88
88
|
message: string;
|
|
89
89
|
};
|
|
90
90
|
|
|
91
|
+
export type LanguageDetectionEvent = {
|
|
92
|
+
/** The language that was detected, in BCP-47 format. e.g. "en-US", "de-DE" */
|
|
93
|
+
detectedLanguage: string;
|
|
94
|
+
/** The confidence of the detected language. A value ranging between 0.0 and 1.0.
|
|
95
|
+
*
|
|
96
|
+
* Values range from:
|
|
97
|
+
*
|
|
98
|
+
* - 1.0 (highly confident)
|
|
99
|
+
* - 0.8 (confident)
|
|
100
|
+
* - 0.5 (not confident)
|
|
101
|
+
* - 0.0 (unknown)
|
|
102
|
+
*/
|
|
103
|
+
confidence: number;
|
|
104
|
+
/** The alternative locales for the same language, in BCP-47 format. e.g. ["en-US", "en-GB"] */
|
|
105
|
+
topLocaleAlternatives: string[];
|
|
106
|
+
};
|
|
107
|
+
|
|
91
108
|
/**
|
|
92
109
|
* Events that are dispatched from the native side
|
|
93
110
|
*/
|
|
@@ -127,6 +144,7 @@ export type ExpoSpeechRecognitionNativeEventMap = {
|
|
|
127
144
|
end: null;
|
|
128
145
|
soundstart: null;
|
|
129
146
|
soundend: null;
|
|
147
|
+
languagedetection: LanguageDetectionEvent;
|
|
130
148
|
volumechange: {
|
|
131
149
|
/**
|
|
132
150
|
* A float value between -2 and 10 indicating the volume of the input audio
|
|
@@ -171,7 +189,9 @@ export type ExpoSpeechRecognitionOptions = {
|
|
|
171
189
|
/**
|
|
172
190
|
* [Default: false] Include punctuation in the recognition results. This applies to full stops and commas.
|
|
173
191
|
*
|
|
174
|
-
* 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+).
|
|
192
|
+
* On Android, this configures [`EXTRA_ENABLE_FORMATTING`](https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_FORMATTING) in the recognizer intent (Android 13+, API level 33+).
|
|
193
|
+
*
|
|
194
|
+
* Note for Android: This feature is only verified to work on Android 13+ with on-device speech recognition enabled (i.e. enabling `requiresOnDeviceRecognition` or using the `com.google.android.as` service package)
|
|
175
195
|
*
|
|
176
196
|
* On iOS, this configures [`SFSpeechRecognitionRequest.addsPunctuation`](https://developer.apple.com/documentation/speech/sfspeechrecognitionrequest/3930023-addspunctuation).
|
|
177
197
|
*/
|
|
@@ -372,6 +392,15 @@ export type AndroidIntentOptions = {
|
|
|
372
392
|
* Depending on the recognizer implementation, this value may have no effect.
|
|
373
393
|
*/
|
|
374
394
|
EXTRA_ENABLE_LANGUAGE_SWITCH: (typeof RecognizerIntentEnableLanguageSwitch)[keyof typeof RecognizerIntentEnableLanguageSwitch];
|
|
395
|
+
/**
|
|
396
|
+
* https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_ENABLE_FORMATTING
|
|
397
|
+
*
|
|
398
|
+
* NOTE: This is also configurable through `addsPunctuation` (which sets `EXTRA_ENABLE_FORMATTING` to "quality")
|
|
399
|
+
*
|
|
400
|
+
* [API level 33] Optional string to enable text formatting (e.g. unspoken punctuation (examples: question mark, comma, period, etc.), capitalization, etc.) and specify the optimization strategy. If set, the partial and final result texts will be formatted. Each result list will contain two hypotheses in the order of 1) formatted text 2) raw text.
|
|
401
|
+
*
|
|
402
|
+
*/
|
|
403
|
+
EXTRA_ENABLE_FORMATTING: "latency" | "quality";
|
|
375
404
|
/**
|
|
376
405
|
* https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_HIDE_PARTIAL_TRAILING_PUNCTUATION
|
|
377
406
|
*
|
|
@@ -528,14 +557,42 @@ export interface ExpoSpeechRecognitionModuleType extends NativeModule {
|
|
|
528
557
|
/**
|
|
529
558
|
* Presents a dialog to the user to request permissions for using speech recognition and the microphone.
|
|
530
559
|
*
|
|
531
|
-
* For
|
|
560
|
+
* For Android, this will request RECORD_AUDIO permission.
|
|
561
|
+
*
|
|
562
|
+
* For iOS, this will request microphone and speech recognition permissions.
|
|
563
|
+
* Once a user has granted (or denied) permissions by responding to the original permission request dialog,
|
|
532
564
|
* the only way that the permissions can be changed is by the user themselves using the device settings app.
|
|
533
565
|
*/
|
|
534
566
|
requestPermissionsAsync(): Promise<PermissionResponse>;
|
|
535
567
|
/**
|
|
536
|
-
* Returns the current permission status for
|
|
568
|
+
* Returns the current permission status for speech recognition and the microphone.
|
|
569
|
+
*
|
|
570
|
+
* You may also use `getMicrophonePermissionsAsync` and `getSpeechRecognizerPermissionsAsync` to get the permissions separately.
|
|
537
571
|
*/
|
|
538
572
|
getPermissionsAsync(): Promise<PermissionResponse>;
|
|
573
|
+
/**
|
|
574
|
+
* Returns the current permission status for the microphone.
|
|
575
|
+
*/
|
|
576
|
+
getMicrophonePermissionsAsync(): Promise<PermissionResponse>;
|
|
577
|
+
/**
|
|
578
|
+
* Presents a dialog to the user to request permissions for using the microphone.
|
|
579
|
+
*
|
|
580
|
+
* For iOS, once a user has granted (or denied) permissions by responding to the original permission request dialog,
|
|
581
|
+
* the only way that the permissions can be changed is by the user themselves using the device settings app.
|
|
582
|
+
*/
|
|
583
|
+
requestMicrophonePermissionsAsync(): Promise<PermissionResponse>;
|
|
584
|
+
/**
|
|
585
|
+
* Returns the current permission status for speech recognition.
|
|
586
|
+
*/
|
|
587
|
+
getSpeechRecognizerPermissionsAsync(): Promise<PermissionResponse>;
|
|
588
|
+
/**
|
|
589
|
+
* [iOS only] Presents a dialog to the user to request permissions for using the speech recognizer.
|
|
590
|
+
* This permission is required when `requiresOnDeviceRecognition` is disabled (i.e. network-based recognition)
|
|
591
|
+
*
|
|
592
|
+
* For iOS, once a user has granted (or denied) permissions by responding to the original permission request dialog,
|
|
593
|
+
* the only way that the permissions can be changed is by the user themselves using the device settings app.
|
|
594
|
+
*/
|
|
595
|
+
requestSpeechRecognizerPermissionsAsync(): Promise<PermissionResponse>;
|
|
539
596
|
/**
|
|
540
597
|
* Returns an array of locales supported by the speech recognizer.
|
|
541
598
|
*
|