expo-speech-recognition 58.1.1 → 58.1.2
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/android/src/main/java/expo/modules/speechrecognition/DelayedFileStreamer.kt +0 -1
- package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionModule.kt +0 -2
- package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechService.kt +45 -14
- package/ios/ExpoSpeechRecognitionModule.swift +51 -12
- package/ios/ExpoSpeechRecognizer.swift +78 -42
- package/package.json +1 -1
|
@@ -217,7 +217,6 @@ class ExpoSpeechRecognitionModule : Module() {
|
|
|
217
217
|
}
|
|
218
218
|
|
|
219
219
|
Function("abort") {
|
|
220
|
-
sendEvent("error", mapOf("error" to "aborted", "message" to "Speech recognition aborted.", "code" to -1))
|
|
221
220
|
expoSpeechService.abort()
|
|
222
221
|
}
|
|
223
222
|
|
|
@@ -440,7 +439,6 @@ class ExpoSpeechRecognitionModule : Module() {
|
|
|
440
439
|
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
|
|
441
440
|
object : RecognitionSupportCallback {
|
|
442
441
|
override fun onSupportResult(recognitionSupport: RecognitionSupport) {
|
|
443
|
-
Log.d("ExpoSpeechService", "onSupportResult() called with recognitionSupport: $recognitionSupport")
|
|
444
442
|
if (!settled.compareAndSet(false, true)) {
|
|
445
443
|
return
|
|
446
444
|
}
|
|
@@ -19,6 +19,7 @@ import android.util.Log
|
|
|
19
19
|
import java.io.File
|
|
20
20
|
import java.net.URI
|
|
21
21
|
import java.util.Locale
|
|
22
|
+
import java.util.concurrent.atomic.AtomicInteger
|
|
22
23
|
|
|
23
24
|
data class SpeechRecognitionErrorEvent(
|
|
24
25
|
val error: String,
|
|
@@ -51,6 +52,12 @@ class ExpoSpeechService(
|
|
|
51
52
|
private val mainHandler = Handler(Looper.getMainLooper())
|
|
52
53
|
|
|
53
54
|
private lateinit var options: SpeechRecognitionOptions
|
|
55
|
+
|
|
56
|
+
/** Bumped by start() and abort(), so that abort() cancels a start() that hasn't run yet */
|
|
57
|
+
private val startGeneration = AtomicInteger()
|
|
58
|
+
|
|
59
|
+
/** Whether "audiostart" was emitted without a matching "audioend" yet */
|
|
60
|
+
private var hasEmittedAudioStart = false
|
|
54
61
|
private var lastVolumeChangeEventTime: Long = 0L
|
|
55
62
|
|
|
56
63
|
/** Audio recorder for persisting audio */
|
|
@@ -115,7 +122,12 @@ class ExpoSpeechService(
|
|
|
115
122
|
/** Starts speech recognition */
|
|
116
123
|
fun start(options: SpeechRecognitionOptions) {
|
|
117
124
|
this.options = options
|
|
125
|
+
val generation = startGeneration.incrementAndGet()
|
|
118
126
|
mainHandler.post {
|
|
127
|
+
if (generation != startGeneration.get()) {
|
|
128
|
+
// abort() or a newer start() was called before this one ran
|
|
129
|
+
return@post
|
|
130
|
+
}
|
|
119
131
|
log("Start recognition.")
|
|
120
132
|
|
|
121
133
|
// Destroy any previous SpeechRecognizer / audio recorder
|
|
@@ -151,6 +163,7 @@ class ExpoSpeechService(
|
|
|
151
163
|
|
|
152
164
|
delayedFileStreamer?.startStreaming()
|
|
153
165
|
|
|
166
|
+
hasEmittedAudioStart = true
|
|
154
167
|
sendEvent(
|
|
155
168
|
"audiostart",
|
|
156
169
|
mapOf(
|
|
@@ -178,6 +191,11 @@ class ExpoSpeechService(
|
|
|
178
191
|
*/
|
|
179
192
|
private fun stopRecording() {
|
|
180
193
|
audioRecorder?.stop()
|
|
194
|
+
if (!hasEmittedAudioStart) {
|
|
195
|
+
audioRecorder = null
|
|
196
|
+
return
|
|
197
|
+
}
|
|
198
|
+
hasEmittedAudioStart = false
|
|
181
199
|
val timestamp = audioRecorder?.stoppedAtMillis ?: System.currentTimeMillis()
|
|
182
200
|
if (audioRecorder?.outputFile != null) {
|
|
183
201
|
val uri = audioRecorder?.outputFile?.absolutePath?.let { "file://$it" }
|
|
@@ -206,6 +224,11 @@ class ExpoSpeechService(
|
|
|
206
224
|
*/
|
|
207
225
|
fun stop() {
|
|
208
226
|
mainHandler.post {
|
|
227
|
+
if (speech == null) {
|
|
228
|
+
// Nothing is running, e.g. recognition ended just before this call
|
|
229
|
+
teardownAndEnd()
|
|
230
|
+
return@post
|
|
231
|
+
}
|
|
209
232
|
recognitionState = RecognitionState.STOPPING
|
|
210
233
|
try {
|
|
211
234
|
speech?.stopListening()
|
|
@@ -223,6 +246,11 @@ class ExpoSpeechService(
|
|
|
223
246
|
* final result is emitted.
|
|
224
247
|
*/
|
|
225
248
|
fun abort() {
|
|
249
|
+
startGeneration.incrementAndGet()
|
|
250
|
+
// Posted, so that it can't overtake the events of a start() that is running on the main thread
|
|
251
|
+
mainHandler.post {
|
|
252
|
+
sendEvent("error", mapOf("error" to "aborted", "message" to "Speech recognition aborted.", "code" to -1))
|
|
253
|
+
}
|
|
226
254
|
teardownAndEnd()
|
|
227
255
|
}
|
|
228
256
|
|
|
@@ -237,10 +265,22 @@ class ExpoSpeechService(
|
|
|
237
265
|
|
|
238
266
|
/**
|
|
239
267
|
* Stops speech recognition, recording and updates state
|
|
268
|
+
*
|
|
269
|
+
* @param onlyIfActive Skip the teardown when the session has already been torn down.
|
|
270
|
+
* Recognizer callbacks can overlap (e.g. onError + onEndOfSegmentedSession) and should emit a single "end" event.
|
|
240
271
|
*/
|
|
241
|
-
private fun teardownAndEnd(
|
|
272
|
+
private fun teardownAndEnd(
|
|
273
|
+
state: RecognitionState = RecognitionState.INACTIVE,
|
|
274
|
+
onlyIfActive: Boolean = false,
|
|
275
|
+
) {
|
|
276
|
+
if (onlyIfActive && speech == null) {
|
|
277
|
+
return
|
|
278
|
+
}
|
|
242
279
|
recognitionState = RecognitionState.STOPPING
|
|
243
280
|
mainHandler.post {
|
|
281
|
+
if (onlyIfActive && speech == null) {
|
|
282
|
+
return@post
|
|
283
|
+
}
|
|
244
284
|
try {
|
|
245
285
|
speech?.cancel()
|
|
246
286
|
} catch (e: Exception) {
|
|
@@ -334,7 +374,6 @@ class ExpoSpeechService(
|
|
|
334
374
|
throw Exception("Audio source is only supported on Android 13 and above")
|
|
335
375
|
}
|
|
336
376
|
|
|
337
|
-
log("Transcribing audio from local file: ${options.audioSource.uri}")
|
|
338
377
|
val file = resolveSourceUri(options.audioSource.uri)
|
|
339
378
|
|
|
340
379
|
// The file should exist, otherwise throw an error
|
|
@@ -381,8 +420,6 @@ class ExpoSpeechService(
|
|
|
381
420
|
if (!contextualStrings.isNullOrEmpty() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
|
382
421
|
// Optional list of strings, towards which the recognizer should bias the recognition results.
|
|
383
422
|
// These are separate from the device context.
|
|
384
|
-
val strings = ArrayList(contextualStrings)
|
|
385
|
-
log("biasing strings: ${strings.joinToString(", ")}")
|
|
386
423
|
intent.putExtra(
|
|
387
424
|
RecognizerIntent.EXTRA_BIASING_STRINGS,
|
|
388
425
|
// List<String> -> ArrayList<java.lang.String>
|
|
@@ -407,8 +444,6 @@ class ExpoSpeechService(
|
|
|
407
444
|
val language = options.lang.takeIf { it.isNotEmpty() } ?: Locale.getDefault().toString()
|
|
408
445
|
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language)
|
|
409
446
|
|
|
410
|
-
log("androidIntentOptions: ${options.androidIntentOptions}")
|
|
411
|
-
|
|
412
447
|
// Add any additional intent extras provided by the user
|
|
413
448
|
options.androidIntentOptions?.forEach { (key, value) ->
|
|
414
449
|
// Use reflection to set the extra
|
|
@@ -416,7 +451,6 @@ class ExpoSpeechService(
|
|
|
416
451
|
val field = RecognizerIntent::class.java.getDeclaredField(key)
|
|
417
452
|
val fieldValue = field.get(null) as? String
|
|
418
453
|
|
|
419
|
-
log("Resolved key $key -> $fieldValue with value: $value (${value.javaClass.name})")
|
|
420
454
|
when (value) {
|
|
421
455
|
is Boolean -> intent.putExtra(fieldValue, value)
|
|
422
456
|
is Int -> intent.putExtra(fieldValue, value)
|
|
@@ -543,7 +577,7 @@ class ExpoSpeechService(
|
|
|
543
577
|
}
|
|
544
578
|
|
|
545
579
|
sendEvent("error", mapOf("error" to errorInfo.error, "message" to errorInfo.message, "code" to error))
|
|
546
|
-
teardownAndEnd(RecognitionState.ERROR)
|
|
580
|
+
teardownAndEnd(RecognitionState.ERROR, onlyIfActive = true)
|
|
547
581
|
log("onError() - ${errorInfo.error}: ${errorInfo.message} - code: $error")
|
|
548
582
|
}
|
|
549
583
|
|
|
@@ -633,9 +667,8 @@ class ExpoSpeechService(
|
|
|
633
667
|
),
|
|
634
668
|
)
|
|
635
669
|
}
|
|
636
|
-
log("onResults(), results: $resultsList")
|
|
637
670
|
|
|
638
|
-
teardownAndEnd()
|
|
671
|
+
teardownAndEnd(onlyIfActive = true)
|
|
639
672
|
}
|
|
640
673
|
|
|
641
674
|
override fun onPartialResults(partialResults: Bundle?) {
|
|
@@ -643,7 +676,6 @@ class ExpoSpeechService(
|
|
|
643
676
|
// Avoid sending result event if there was an empty result, or the first result is an empty string
|
|
644
677
|
val nonEmptyStrings = partialResultsList.filter { it["transcript"]?.toString()?.isNotEmpty() ?: false }
|
|
645
678
|
|
|
646
|
-
log("onPartialResults(), results: $nonEmptyStrings")
|
|
647
679
|
if (nonEmptyStrings.isNotEmpty()) {
|
|
648
680
|
sendEvent("result", mapOf("results" to nonEmptyStrings, "isFinal" to false))
|
|
649
681
|
}
|
|
@@ -685,17 +717,16 @@ class ExpoSpeechService(
|
|
|
685
717
|
),
|
|
686
718
|
)
|
|
687
719
|
}
|
|
688
|
-
log("onSegmentResults(), transcriptions: $resultsList")
|
|
689
720
|
|
|
690
721
|
// If the user opted to stop
|
|
691
722
|
if (recognitionState == RecognitionState.STOPPING) {
|
|
692
|
-
teardownAndEnd()
|
|
723
|
+
teardownAndEnd(onlyIfActive = true)
|
|
693
724
|
}
|
|
694
725
|
}
|
|
695
726
|
|
|
696
727
|
override fun onEndOfSegmentedSession() {
|
|
697
728
|
log("onEndOfSegmentedSession()")
|
|
698
|
-
teardownAndEnd()
|
|
729
|
+
teardownAndEnd(onlyIfActive = true)
|
|
699
730
|
}
|
|
700
731
|
|
|
701
732
|
override fun onEvent(
|
|
@@ -40,7 +40,26 @@ private func legacyResolveBlock(for promise: Promise) -> EXPromiseResolveBlock {
|
|
|
40
40
|
|
|
41
41
|
public class ExpoSpeechRecognitionModule: Module {
|
|
42
42
|
|
|
43
|
-
var speechRecognizer: ExpoSpeechRecognizer?
|
|
43
|
+
@MainActor var speechRecognizer: ExpoSpeechRecognizer?
|
|
44
|
+
|
|
45
|
+
// The pending `start()` call. `stop()` and `abort()` cancel it so that a start that is still
|
|
46
|
+
// waiting on permissions or recognizer setup can't open the microphone afterwards.
|
|
47
|
+
private let startTaskLock = NSLock()
|
|
48
|
+
private var startTask: Task<Void, Never>?
|
|
49
|
+
|
|
50
|
+
private func cancelStartTask() {
|
|
51
|
+
startTaskLock.withLock {
|
|
52
|
+
startTask?.cancel()
|
|
53
|
+
startTask = nil
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private func runStartTask(_ operation: @escaping @MainActor () async -> Void) {
|
|
58
|
+
startTaskLock.withLock {
|
|
59
|
+
startTask?.cancel()
|
|
60
|
+
startTask = Task { await operation() }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
44
63
|
|
|
45
64
|
// Hack for iOS 18 to detect final results
|
|
46
65
|
// See: https://forums.developer.apple.com/forums/thread/762952 for more info
|
|
@@ -63,7 +82,8 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
63
82
|
|
|
64
83
|
OnDestroy {
|
|
65
84
|
// Cancel any running speech recognizers
|
|
66
|
-
|
|
85
|
+
cancelStartTask()
|
|
86
|
+
Task { @MainActor in
|
|
67
87
|
await speechRecognizer?.abort()
|
|
68
88
|
}
|
|
69
89
|
}
|
|
@@ -170,7 +190,7 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
170
190
|
}
|
|
171
191
|
|
|
172
192
|
AsyncFunction("getStateAsync") { (promise: Promise) in
|
|
173
|
-
Task {
|
|
193
|
+
Task { @MainActor in
|
|
174
194
|
let state = await speechRecognizer?.getState()
|
|
175
195
|
promise.resolve(state ?? "inactive")
|
|
176
196
|
}
|
|
@@ -178,15 +198,17 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
178
198
|
|
|
179
199
|
/** Start recognition with args: lang, interimResults, maxAlternatives */
|
|
180
200
|
Function("start") { (options: SpeechRecognitionOptions) in
|
|
181
|
-
|
|
201
|
+
runStartTask { [self] in
|
|
182
202
|
do {
|
|
183
203
|
let currentLocale = await speechRecognizer?.getLocale()
|
|
204
|
+
guard !Task.isCancelled else { return }
|
|
184
205
|
|
|
185
206
|
// Reset the previous result
|
|
186
207
|
self.previousResult = nil
|
|
187
208
|
|
|
188
209
|
// Re-create the speech recognizer when locales change
|
|
189
|
-
|
|
210
|
+
var recognizer = self.speechRecognizer
|
|
211
|
+
if recognizer == nil || currentLocale != options.lang {
|
|
190
212
|
guard let locale = resolveLocale(localeIdentifier: options.lang) else {
|
|
191
213
|
let availableLocales = SFSpeechRecognizer.supportedLocales().map { $0.identifier }
|
|
192
214
|
.joined(separator: ", ")
|
|
@@ -199,13 +221,16 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
199
221
|
return
|
|
200
222
|
}
|
|
201
223
|
|
|
202
|
-
|
|
224
|
+
recognizer = try await ExpoSpeechRecognizer(
|
|
203
225
|
locale: locale
|
|
204
226
|
)
|
|
227
|
+
guard !Task.isCancelled else { return }
|
|
205
228
|
}
|
|
206
229
|
|
|
207
230
|
if !options.requiresOnDeviceRecognition {
|
|
208
|
-
|
|
231
|
+
let authorized = await SFSpeechRecognizer.hasAuthorizationToRecognize()
|
|
232
|
+
guard !Task.isCancelled else { return }
|
|
233
|
+
guard authorized else {
|
|
209
234
|
sendErrorAndStop(
|
|
210
235
|
error: "not-allowed",
|
|
211
236
|
message: RecognizerError.notAuthorizedToRecognize.message
|
|
@@ -214,7 +239,9 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
214
239
|
}
|
|
215
240
|
}
|
|
216
241
|
|
|
217
|
-
|
|
242
|
+
let hasPermissionToRecord = await AVAudioSession.sharedInstance().hasPermissionToRecord()
|
|
243
|
+
guard !Task.isCancelled else { return }
|
|
244
|
+
guard hasPermissionToRecord else {
|
|
218
245
|
sendErrorAndStop(
|
|
219
246
|
error: "not-allowed",
|
|
220
247
|
message: RecognizerError.notPermittedToRecord.message
|
|
@@ -222,8 +249,17 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
222
249
|
return
|
|
223
250
|
}
|
|
224
251
|
|
|
252
|
+
// End the session of the recognizer that is being replaced (the locale changed)
|
|
253
|
+
if let previous = self.speechRecognizer, previous !== recognizer {
|
|
254
|
+
await previous.reset()
|
|
255
|
+
guard !Task.isCancelled else { return }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Stored only now, so `stop()` and `abort()` never find a recognizer without handlers
|
|
259
|
+
self.speechRecognizer = recognizer
|
|
260
|
+
|
|
225
261
|
// Start recognition!
|
|
226
|
-
await
|
|
262
|
+
await recognizer?.start(
|
|
227
263
|
options: options,
|
|
228
264
|
resultHandler: { [weak self] result in
|
|
229
265
|
self?.handleRecognitionResult(result, maxAlternatives: options.maxAlternatives)
|
|
@@ -261,6 +297,7 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
261
297
|
}
|
|
262
298
|
)
|
|
263
299
|
} catch {
|
|
300
|
+
guard !Task.isCancelled else { return }
|
|
264
301
|
self.sendEvent(
|
|
265
302
|
"error",
|
|
266
303
|
[
|
|
@@ -364,9 +401,10 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
364
401
|
}
|
|
365
402
|
|
|
366
403
|
Function("stop") { () -> Void in
|
|
367
|
-
|
|
404
|
+
cancelStartTask()
|
|
405
|
+
Task { @MainActor in
|
|
368
406
|
if let recognizer = speechRecognizer {
|
|
369
|
-
|
|
407
|
+
recognizer.stop()
|
|
370
408
|
} else {
|
|
371
409
|
sendEvent("end")
|
|
372
410
|
}
|
|
@@ -374,7 +412,8 @@ public class ExpoSpeechRecognitionModule: Module {
|
|
|
374
412
|
}
|
|
375
413
|
|
|
376
414
|
Function("abort") { () -> Void in
|
|
377
|
-
|
|
415
|
+
cancelStartTask()
|
|
416
|
+
Task { @MainActor in
|
|
378
417
|
sendEvent("error", ["error": "aborted", "message": "Speech recognition aborted."])
|
|
379
418
|
|
|
380
419
|
if let recognizer = speechRecognizer {
|
|
@@ -47,6 +47,10 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
47
47
|
private var stoppedListening = false
|
|
48
48
|
/// Epoch milliseconds when the audio engine stopped
|
|
49
49
|
private var audioEndTimestampMillis: Double?
|
|
50
|
+
/// Whether "audiostart" was emitted without a matching "audioend" yet
|
|
51
|
+
private var hasEmittedAudioStart = false
|
|
52
|
+
/// Identifies the current recognition task, so that callbacks from a replaced task can be ignored
|
|
53
|
+
private var recognitionGeneration = 0
|
|
50
54
|
|
|
51
55
|
/// Detection timer, for non-continuous speech recognition
|
|
52
56
|
@MainActor var detectionTimer: Timer?
|
|
@@ -137,21 +141,20 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
137
141
|
audioStartHandler: @escaping (String?, Double) -> Void,
|
|
138
142
|
audioEndHandler: @escaping (String?, Double) -> Void,
|
|
139
143
|
volumeChangeHandler: @escaping (Float) -> Void
|
|
140
|
-
) {
|
|
144
|
+
) async {
|
|
141
145
|
self.endHandler = endHandler
|
|
142
146
|
self.audioEndHandler = audioEndHandler
|
|
143
147
|
self.volumeChangeHandler = volumeChangeHandler
|
|
144
148
|
self.errorHandler = errorHandler
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
}
|
|
149
|
+
// Awaited rather than spawned, so the caller's cancellation still applies after the actor hop.
|
|
150
|
+
await startRecognizer(
|
|
151
|
+
options: options,
|
|
152
|
+
resultHandler: resultHandler,
|
|
153
|
+
errorHandler: errorHandler,
|
|
154
|
+
startHandler: startHandler,
|
|
155
|
+
speechStartHandler: speechStartHandler,
|
|
156
|
+
audioStartHandler: audioStartHandler
|
|
157
|
+
)
|
|
155
158
|
}
|
|
156
159
|
|
|
157
160
|
/// Stops the speech recognizer.
|
|
@@ -173,10 +176,8 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
173
176
|
/// Cancels the current speech recognition task.
|
|
174
177
|
/// This is different from `stop` in that the recognition task is immediately cancelled and no
|
|
175
178
|
/// final result is emitted.
|
|
176
|
-
@MainActor func abort() {
|
|
177
|
-
|
|
178
|
-
await reset(andEmitEnd: true)
|
|
179
|
-
}
|
|
179
|
+
@MainActor func abort() async {
|
|
180
|
+
await reset(andEmitEnd: true)
|
|
180
181
|
}
|
|
181
182
|
|
|
182
183
|
///
|
|
@@ -210,6 +211,7 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
210
211
|
speechStartHandler: @escaping () -> Void,
|
|
211
212
|
audioStartHandler: @escaping (String?, Double) -> Void
|
|
212
213
|
) {
|
|
214
|
+
guard !Task.isCancelled else { return }
|
|
213
215
|
// Reset the speech recognizer before starting
|
|
214
216
|
reset(andEmitEnd: false)
|
|
215
217
|
|
|
@@ -244,6 +246,7 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
244
246
|
} else {
|
|
245
247
|
try prepareMicrophoneRecognition(request: request, options: options)
|
|
246
248
|
}
|
|
249
|
+
try Task.checkCancellation()
|
|
247
250
|
let audioStartTimestampMillis = Date().timeIntervalSince1970 * 1000
|
|
248
251
|
|
|
249
252
|
startRecognitionTask(
|
|
@@ -256,11 +259,20 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
256
259
|
isSourcedFromFile: isSourcedFromFile
|
|
257
260
|
)
|
|
258
261
|
|
|
259
|
-
|
|
260
|
-
|
|
262
|
+
hasEmittedAudioStart = true
|
|
263
|
+
let outputFilePath = outputFileUrl?.absoluteString
|
|
264
|
+
// Emitted from the main actor, like "end", so that on a restart
|
|
265
|
+
// the previous session's "end" can't arrive after this "start"
|
|
266
|
+
Task { @MainActor in
|
|
267
|
+
// Emit the "start" event to indicate that speech recognition has started
|
|
268
|
+
startHandler()
|
|
261
269
|
|
|
262
|
-
|
|
263
|
-
|
|
270
|
+
// If user has opted in to recording, emit an "audiostart" event with the path
|
|
271
|
+
audioStartHandler(outputFilePath, audioStartTimestampMillis)
|
|
272
|
+
}
|
|
273
|
+
} catch is CancellationError {
|
|
274
|
+
// `stop()` or `abort()` cancelled this start during setup. They emit the "end" event.
|
|
275
|
+
reset(andEmitEnd: false)
|
|
264
276
|
} catch {
|
|
265
277
|
errorHandler(error)
|
|
266
278
|
reset(andEmitEnd: true)
|
|
@@ -278,11 +290,14 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
278
290
|
) {
|
|
279
291
|
let audioEngine = self.audioEngine
|
|
280
292
|
let shouldRunTimers = !continuous && !isSourcedFromFile
|
|
293
|
+
recognitionGeneration += 1
|
|
294
|
+
let generation = recognitionGeneration
|
|
281
295
|
|
|
282
296
|
self.task = recognizer.recognitionTask(
|
|
283
297
|
with: request,
|
|
284
298
|
resultHandler: { [weak self] result, error in
|
|
285
299
|
self?.recognitionHandler(
|
|
300
|
+
generation: generation,
|
|
286
301
|
audioEngine: audioEngine,
|
|
287
302
|
result: result,
|
|
288
303
|
error: error,
|
|
@@ -348,6 +363,8 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
348
363
|
options: SpeechRecognitionOptions
|
|
349
364
|
) throws {
|
|
350
365
|
try Self.setupAudioSession(options.iosCategory)
|
|
366
|
+
// Setting up the audio session is slow. Don't open the microphone if the start was cancelled meanwhile.
|
|
367
|
+
try Task.checkCancellation()
|
|
351
368
|
registerAudioSessionObservers()
|
|
352
369
|
self.audioEngine = AVAudioEngine()
|
|
353
370
|
|
|
@@ -500,12 +517,15 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
500
517
|
let filePath = self.outputFileUrl?.absoluteString
|
|
501
518
|
let timestamp = audioEndTimestampMillis ?? Date().timeIntervalSince1970 * 1000
|
|
502
519
|
outputFileUrl = nil
|
|
503
|
-
|
|
504
|
-
|
|
520
|
+
let shouldEmitAudioEnd = hasEmittedAudioStart
|
|
521
|
+
hasEmittedAudioStart = false
|
|
522
|
+
// Not a plain `Task {}`: that would first wait for this actor, which a restart keeps busy,
|
|
523
|
+
// and deliver the "end" of the previous session after the "start" of the new one
|
|
524
|
+
Task { @MainActor in
|
|
525
|
+
if shouldEmitAudioEnd {
|
|
505
526
|
self.audioEndHandler?(filePath, timestamp)
|
|
506
|
-
self.audioEndHandler = nil
|
|
507
|
-
self.endHandler?()
|
|
508
527
|
}
|
|
528
|
+
self.endHandler?()
|
|
509
529
|
}
|
|
510
530
|
}
|
|
511
531
|
|
|
@@ -533,7 +553,7 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
533
553
|
}
|
|
534
554
|
|
|
535
555
|
/// Reset the speech recognizer.
|
|
536
|
-
|
|
556
|
+
func reset(andEmitEnd: Bool = false) {
|
|
537
557
|
let taskWasRunning = task != nil
|
|
538
558
|
let shouldEmitEndEvent = andEmitEnd || taskWasRunning || stoppedListening
|
|
539
559
|
|
|
@@ -575,9 +595,6 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
575
595
|
// (e.g. in the case of a setup error)
|
|
576
596
|
print("SpeechRecognizer: end")
|
|
577
597
|
if shouldEmitEndEvent {
|
|
578
|
-
Task { @MainActor in
|
|
579
|
-
self.errorHandler = nil
|
|
580
|
-
}
|
|
581
598
|
end()
|
|
582
599
|
}
|
|
583
600
|
audioEndTimestampMillis = nil
|
|
@@ -746,12 +763,8 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
746
763
|
Task { [weak self] in
|
|
747
764
|
let typeValue = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt
|
|
748
765
|
let type = typeValue.flatMap(AVAudioSession.InterruptionType.init(rawValue:))
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
// Emit "interrupted" error event
|
|
752
|
-
await self?.emitError(.audioSessionInterrupted)
|
|
753
|
-
// Force-stop the recognition task and emit the "end" event
|
|
754
|
-
await self?.reset(andEmitEnd: true)
|
|
766
|
+
if type == .began {
|
|
767
|
+
await self?.handleAudioInterruptionBegan()
|
|
755
768
|
}
|
|
756
769
|
}
|
|
757
770
|
}
|
|
@@ -763,17 +776,27 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
763
776
|
) { [weak self] _ in
|
|
764
777
|
let appState = UIApplication.shared.applicationState
|
|
765
778
|
Task { [weak self] in
|
|
766
|
-
|
|
767
|
-
await self?.handleAudioRouteChange(taskState: taskState, appState: appState)
|
|
779
|
+
await self?.handleAudioRouteChange(appState: appState)
|
|
768
780
|
}
|
|
769
781
|
}
|
|
770
782
|
|
|
771
783
|
}
|
|
772
784
|
|
|
773
|
-
private func
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
785
|
+
private func handleAudioInterruptionBegan() {
|
|
786
|
+
// Read the task state here, on the actor, so it can't go stale before we act on it
|
|
787
|
+
let taskState = task?.state
|
|
788
|
+
guard taskState == .running || taskState == .starting else {
|
|
789
|
+
return
|
|
790
|
+
}
|
|
791
|
+
// Emit "interrupted" error event
|
|
792
|
+
emitError(.audioSessionInterrupted)
|
|
793
|
+
// Force-stop the recognition task and emit the "end" event
|
|
794
|
+
reset(andEmitEnd: true)
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
private func handleAudioRouteChange(appState: UIApplication.State) {
|
|
798
|
+
// Read the task state here, on the actor, so it can't go stale before we act on it
|
|
799
|
+
let taskState = task?.state
|
|
777
800
|
// We only care about route changes when the recognizer is active
|
|
778
801
|
if taskState == .running || taskState == .starting {
|
|
779
802
|
// App deactivation can emit a route change while the audio session is
|
|
@@ -927,7 +950,20 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
927
950
|
ExtAudioFileWrite(audioFileRef, convertedBuffer.frameLength, convertedBuffer.audioBufferList)
|
|
928
951
|
}
|
|
929
952
|
|
|
953
|
+
/// The recognition task for `generation`, or nil once it has ended or been replaced by a newer one
|
|
954
|
+
private func task(forGeneration generation: Int) -> SFSpeechRecognitionTask? {
|
|
955
|
+
return generation == recognitionGeneration ? task : nil
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
private func reset(ifGeneration generation: Int) {
|
|
959
|
+
guard generation == recognitionGeneration else {
|
|
960
|
+
return
|
|
961
|
+
}
|
|
962
|
+
reset()
|
|
963
|
+
}
|
|
964
|
+
|
|
930
965
|
nonisolated private func recognitionHandler(
|
|
966
|
+
generation: Int,
|
|
931
967
|
audioEngine: AVAudioEngine?,
|
|
932
968
|
result: SFSpeechRecognitionResult?,
|
|
933
969
|
error: Error?,
|
|
@@ -954,7 +990,7 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
954
990
|
|
|
955
991
|
if let result: SFSpeechRecognitionResult, shouldEmitResult {
|
|
956
992
|
Task { @MainActor in
|
|
957
|
-
let taskState = await task?.state
|
|
993
|
+
let taskState = await task(forGeneration: generation)?.state
|
|
958
994
|
// Make sure the task is running before emitting the result
|
|
959
995
|
if taskState != .none {
|
|
960
996
|
resultHandler(result)
|
|
@@ -965,7 +1001,7 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
965
1001
|
if let error: Error {
|
|
966
1002
|
// TODO: don't emit no-speech if there were already interim results
|
|
967
1003
|
Task { @MainActor in
|
|
968
|
-
if await task != nil {
|
|
1004
|
+
if await task(forGeneration: generation) != nil {
|
|
969
1005
|
// Don't emit any errors after the task has finished
|
|
970
1006
|
errorHandler(error)
|
|
971
1007
|
}
|
|
@@ -976,7 +1012,7 @@ actor ExpoSpeechRecognizer: ObservableObject {
|
|
|
976
1012
|
|| receivedFinalResult
|
|
977
1013
|
{
|
|
978
1014
|
Task { @MainActor in
|
|
979
|
-
await reset()
|
|
1015
|
+
await reset(ifGeneration: generation)
|
|
980
1016
|
}
|
|
981
1017
|
return
|
|
982
1018
|
}
|