expo-speech-recognition 1.0.1 → 1.1.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 CHANGED
@@ -1,10 +1,18 @@
1
1
  # expo-speech-recognition
2
2
 
3
+ ## 1.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 7fa9bc6: Implemented long form file-based transcriptions for iOS. This change circumvents the undocumented 1-minute limitation in [`SFSpeechURLRecognitionRequest
8
+ `](https://developer.apple.com/documentation/speech/sfspeechurlrecognitionrequest).
9
+
3
10
  ## 1.0.1
4
11
 
5
12
  ### Patch Changes
6
13
 
7
14
  - e4c54f1: Fixed handling of interim and final results on web
15
+ - d3d3d63: Separate microphone and recognizer permissions
8
16
 
9
17
  ## 1.0.0
10
18
 
package/README.md CHANGED
@@ -33,8 +33,12 @@ expo-speech-recognition implements the iOS [`SFSpeechRecognizer`](https://develo
33
33
  - [start()](#startoptions-speechrecognitionoptions-void)
34
34
  - [stop()](#stop-void)
35
35
  - [abort()](#abort-void)
36
- - [requestPermissionsAsync()](#requestpermissionsasync-promisepermissionresponse)
37
- - [getPermissionsAsync()](#getpermissionsasync-promisepermissionresponse)
36
+ - [requestPermissionsAsync()](#requestpermissionsasync)
37
+ - [requestMicrophonePermissionsAsync()](#requestmicrophonepermissionsasync)
38
+ - [requestSpeechRecognizerPermissionsAsync()](#requestspeechrecognizerpermissionsasync)
39
+ - [getPermissionsAsync()](#getpermissionsasync)
40
+ - [getMicrophonePermissionsAsync()](#getmicrophonepermissionsasync)
41
+ - [getSpeechRecognizerPermissionsAsync()](#getspeechrecognizerpermissionsasync)
38
42
  - [getStateAsync()](#getstateasync-promisespeechrecognitionstate)
39
43
  - [getSupportedLocales()](#getsupportedlocales)
40
44
  - [getSpeechRecognitionServices()](#getspeechrecognitionservices-string-android-only)
@@ -60,7 +64,6 @@ npm install expo-speech-recognition@sdk-51
60
64
  npm install expo-speech-recognition@sdk-50
61
65
  ```
62
66
 
63
-
64
67
  2. Configure the config plugin.
65
68
 
66
69
  > 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.
@@ -482,7 +485,7 @@ function AudioPlayer(props: { source: string }) {
482
485
  > [!IMPORTANT]
483
486
  > This feature is available on Android 13+ and iOS. If the device does not support the feature, you'll receive an `error` event with the code `audio-capture`.
484
487
 
485
- Instead of using the microphone, you can configure the `audioSource.uri` option to transcribe audio files.
488
+ Instead of using the microphone, you can configure the `audioSource.uri` option to transcribe audio files. For long-form audio files, you will likely want to use on-device recognition instead of network-based recognition which you can opt-in via `requiresOnDeviceRecognition`. For Android, you should first check if the user has the speech model installed with `getSupportedLocales()`.
486
489
 
487
490
  ### Supported input audio formats
488
491
 
@@ -497,8 +500,6 @@ The following audio formats have been verified on a Samsung Galaxy S23 Ultra on
497
500
 
498
501
  #### iOS
499
502
 
500
- > Due to a limitation in the underlying `SFSpeechURLRecognitionRequest` API, file-based transcription will only transcribe the **first 1 minute of the audio file**.
501
-
502
503
  The following audio formats have been verified on an iPhone 15 Pro Max on iOS 17.5:
503
504
 
504
505
  - 16000hz 16-bit 1-channel PCM WAV ([example file](https://github.com/jamsch/expo-speech-recognition/blob/main/example/assets/audio-remote/remote-en-us-sentence-16000hz-pcm_s16le.wav))
@@ -521,6 +522,8 @@ function TranscribeAudioFile() {
521
522
  ExpoSpeechRecognitionModule.start({
522
523
  lang: "en-US",
523
524
  interimResults: true,
525
+ // Recommended: true on iOS, false on Android, unless the speech model is installed, which you can check with `getSupportedLocales()`
526
+ requiresOnDeviceRecognition: Platform.OS === "ios",
524
527
  audioSource: {
525
528
  /** Local file URI */
526
529
  uri: "file:///path/to/audio.wav",
@@ -531,7 +534,7 @@ function TranscribeAudioFile() {
531
534
  /** [Android only] Audio sampling rate in Hz. */
532
535
  sampleRate: 16000,
533
536
  /**
534
- * [Android only] The delay between chunks of audio to stream to the speech recognition service.
537
+ * The delay between chunks of audio to stream to the speech recognition service.
535
538
  * Use this setting to avoid being rate-limited when using network-based recognition.
536
539
  * If you're using on-device recognition, you may want to increase this value to avoid unprocessed audio chunks.
537
540
  * Default: 50ms for network-based recognition, 15ms for on-device recognition
@@ -542,7 +545,7 @@ function TranscribeAudioFile() {
542
545
  };
543
546
 
544
547
  useSpeechRecognitionEvent("result", (ev) => {
545
- // Note: multiple final results will likely be returned on Android
548
+ // Note: multiple final results will likely be returned
546
549
  // so you'll need to concatenate previous final results
547
550
  setTranscription(ev.results[0]?.transcript || "");
548
551
  });
@@ -837,11 +840,16 @@ ExpoSpeechRecognitionModule.abort();
837
840
  // Expect an "error" event to be emitted with the code "aborted"
838
841
  ```
839
842
 
840
- ### `requestPermissionsAsync(): Promise<PermissionResponse>`
843
+ ### `requestPermissionsAsync()`
841
844
 
842
845
  Presents a dialog to the user to request the necessary permissions.
843
846
 
844
- For iOS, this requests two permissions: record permissions (to access the microphone), and speech recognition permissions. Once a user has granted (or denied) permissions by responding to the original permission request dialog, the only way that the permissions can be changed is by the user themselves using the device settings app.
847
+ - On Android, this requests [`RECORD_AUDIO`](https://developer.android.com/reference/android/Manifest.permission#RECORD_AUDIO) permissions.
848
+ - On iOS, this requests two permissions: [`AVAudioSession.RecordPermission`](https://developer.apple.com/documentation/avfaudio/avaudiosession/recordpermission) and [`SFSpeechRecognizer.requestAuthorization()`](https://developer.apple.com/documentation/speech/sfspeechrecognizer/1649892-requestauthorization).
849
+
850
+ If you're using on-device recognition on iOS, you just need to request microphone permissions, which can be called with [`requestMicrophonePermissionsAsync()`](#requestmicrophonepermissionsasync).
851
+
852
+ Once a user has granted (or denied) permissions by responding to the original permission request dialog, the only way that the permissions can be changed is by the user themselves using the device settings app.
845
853
 
846
854
  ```ts
847
855
  import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
@@ -854,9 +862,55 @@ ExpoSpeechRecognitionModule.requestPermissionsAsync().then((result) => {
854
862
  });
855
863
  ```
856
864
 
857
- ### `getPermissionsAsync(): Promise<PermissionResponse>`
865
+ ### `requestMicrophonePermissionsAsync()`
866
+
867
+ Requests permissions to use the microphone.
868
+
869
+ - On iOS, this requests [`AVAudioSession.RecordPermission`](https://developer.apple.com/documentation/avfaudio/avaudiosession/recordpermission) permissions.
870
+ - On Android, this requests [`RECORD_AUDIO`](https://developer.android.com/reference/android/Manifest.permission#RECORD_AUDIO) permissions.
871
+
872
+ ```ts
873
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
874
+
875
+ ExpoSpeechRecognitionModule.requestMicrophonePermissionsAsync().then(
876
+ (result) => {
877
+ console.log("Status:", result.status); // "granted" | "denied" | "not-determined"
878
+ console.log("Granted:", result.granted); // true | false
879
+ console.log("Can ask again:", result.canAskAgain); // true | false
880
+ console.log("Expires:", result.expires); // "never" | number
881
+ },
882
+ );
883
+ ```
884
+
885
+ ### `requestSpeechRecognizerPermissionsAsync()`
886
+
887
+ > [!NOTE]
888
+ > This is only supported on iOS. Request this permission only if you aren't using on-device recognition.
889
+
890
+ Requests [`SFSpeechRecognizer.requestAuthorization()`](https://developer.apple.com/documentation/speech/sfspeechrecognizer/1649892-requestauthorization) permissions before sending voice data across the network to Apple's servers for transcription.
891
+
892
+ ```ts
893
+ import { Platform } from "react-native";
894
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
895
+
896
+ const requiresOnDeviceRecognition = false;
897
+
898
+ // We only need this permission when network-based recognition is used on iOS
899
+ if (!requiresOnDeviceRecognition && Platform.OS === "ios") {
900
+ ExpoSpeechRecognitionModule.requestSpeechRecognizerPermissionsAsync().then(
901
+ (result) => {
902
+ console.log("Status:", result.status); // "granted" | "denied" | "not-determined"
903
+ console.log("Granted:", result.granted); // true | false
904
+ console.log("Can ask again:", result.canAskAgain); // true | false
905
+ console.log("Expires:", result.expires); // "never" | number
906
+ },
907
+ );
908
+ }
909
+ ```
910
+
911
+ ### `getPermissionsAsync()`
858
912
 
859
- Returns the current permission status for the microphone and speech recognition.
913
+ Returns the current permission status for both microphone and iOS speech recognizer.
860
914
 
861
915
  ```ts
862
916
  import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
@@ -869,6 +923,41 @@ ExpoSpeechRecognitionModule.getPermissionsAsync().then((result) => {
869
923
  });
870
924
  ```
871
925
 
926
+ ### `getMicrophonePermissionsAsync()`
927
+
928
+ Returns the current permission status for the microphone. On Android, this checks the [`RECORD_AUDIO`](https://developer.android.com/reference/android/Manifest.permission#RECORD_AUDIO) permissions. On iOS this checks the [`AVAudioSession.RecordPermission`](https://developer.apple.com/documentation/avfaudio/avaudiosession/recordpermission) permissions.
929
+
930
+ ```ts
931
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
932
+
933
+ ExpoSpeechRecognitionModule.getMicrophonePermissionsAsync().then((result) => {
934
+ console.log("Status:", result.status); // "granted" | "denied" | "not-determined"
935
+ console.log("Granted:", result.granted); // true | false
936
+ console.log("Can ask again:", result.canAskAgain); // true | false
937
+ console.log("Expires:", result.expires); // "never" | number
938
+ });
939
+ ```
940
+
941
+ ### `getSpeechRecognizerPermissionsAsync()`
942
+
943
+ > [!NOTE]
944
+ > This is only supported on iOS.
945
+
946
+ Checks the current permissions to use network-based recognition for [`SFSpeechRecognizer`](https://developer.apple.com/documentation/speech/sfspeechrecognizer) for iOS.
947
+
948
+ ```ts
949
+ import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";
950
+
951
+ ExpoSpeechRecognitionModule.getSpeechRecognizerPermissionsAsync().then(
952
+ (result) => {
953
+ console.log("Status:", result.status); // "granted" | "denied" | "not-determined"
954
+ console.log("Granted:", result.granted); // true | false
955
+ console.log("Can ask again:", result.canAskAgain); // true | false
956
+ console.log("Expires:", result.expires); // "never" | number
957
+ },
958
+ );
959
+ ```
960
+
872
961
  ### `getStateAsync(): Promise<SpeechRecognitionState>`
873
962
 
874
963
  Returns the current internal state of the speech recognizer.
@@ -92,8 +92,6 @@ 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 there's results (as a string array, not API compliant)
96
- "result",
97
95
  // Called when the language detection (and switching) results are available.
98
96
  "languagedetection",
99
97
  // Fired when the input volume changes
@@ -199,6 +199,8 @@ actor ExpoSpeechRecognizer: ObservableObject {
199
199
  // Reset the speech recognizer before starting
200
200
  reset(andEmitEnd: false)
201
201
 
202
+ self.options = options
203
+ self.request = nil
202
204
  self.outputFileUrl = nil
203
205
  self.speechStartHandler = speechStartHandler
204
206
 
@@ -214,118 +216,166 @@ actor ExpoSpeechRecognizer: ObservableObject {
214
216
  recognizer: recognizer
215
217
  )
216
218
  self.request = request
217
-
218
- // Check if options.audioSource is set, if it is, then it is sourced from a file
219
219
  let isSourcedFromFile = options.audioSource?.uri != nil
220
220
 
221
- if isSourcedFromFile {
222
- // If we're doing file-based recognition we don't need to create an audio engine
223
- self.audioEngine = nil
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)!)
224
224
  } else {
225
- // Set up the audio session to get the correct audio format
226
- try Self.setupAudioSession(options.iosCategory)
227
-
228
- self.audioEngine = AVAudioEngine()
225
+ try prepareMicrophoneRecognition(request: request, options: options)
226
+ }
229
227
 
230
- guard let audioEngine = self.audioEngine else {
231
- print("expo-speech-recognition: ERROR - Failed to create AVAudioEngine")
232
- throw RecognizerError.invalidAudioSource
233
- }
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
+ )
234
237
 
235
- let inputNode = audioEngine.inputNode
236
- // Note: accessing `inputNode.outputFormat(forBus: 0)` may crash the thread with the error:
237
- // `required condition is false: format.sampleRate == hwFormat.sampleRate`
238
- // (under the hood it calls `AVAudioEngineImpl::UpdateInputNode` -> `AVAudioNode setOutputFormat:forBus:0`)
239
- let audioFormat = Self.getAudioFormat(forEngine: audioEngine)
238
+ // Emit the "start" event to indicate that speech recognition has started
239
+ startHandler()
240
240
 
241
- // Check if the microphone is busy
242
- guard !Self.audioInputIsBusy(audioFormat) else {
243
- print(
244
- "expo-speech-recognition: ERROR - input is busy \(audioFormat)"
245
- )
246
- throw RecognizerError.audioInputBusy
247
- }
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
+ }
248
248
 
249
- let mixerNode = AVAudioMixerNode()
250
- audioEngine.attach(mixerNode)
251
- audioEngine.connect(inputNode, to: mixerNode, format: audioFormat)
252
-
253
- // Feature: file recording
254
- if options.recordingOptions?.persist == true {
255
- guard
256
- let fileAudioFormat = Self.getFileAudioFormat(
257
- options: options,
258
- engine: audioEngine
259
- )
260
- else {
261
- print(
262
- "expo-speech-recognition: ERROR - Failed to create AVAudioFormat from given sample rate"
263
- )
264
- throw RecognizerError.invalidAudioSource
265
- }
266
-
267
- let outputUrl = prepareFileWriter(
268
- outputDirectory: options.recordingOptions?.outputDirectory,
269
- outputFileName: options.recordingOptions?.outputFileName,
270
- audioFormat: fileAudioFormat
271
- )
272
- self.outputFileUrl = outputUrl
273
- }
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
274
260
 
275
- // Set up audio recording & sink to recognizer/file
276
- try Self.prepareEngine(
261
+ self.task = recognizer.recognitionTask(
262
+ with: request,
263
+ resultHandler: { [weak self] result, error in
264
+ self?.recognitionHandler(
277
265
  audioEngine: audioEngine,
278
- mixerNode: mixerNode,
279
- options: options,
280
- request: request,
281
- audioFileRef: self.audioFileRef,
282
- volumeChangeHandler: { volume in
283
- Task { @MainActor in
284
- self.volumeChangeHandler?(volume)
285
- }
286
- }
266
+ result: result,
267
+ error: error,
268
+ resultHandler: resultHandler,
269
+ errorHandler: errorHandler,
270
+ continuous: continuous,
271
+ shouldRunTimers: shouldRunTimers,
272
+ canEmitInterimResults: canEmitInterimResults,
273
+ isSourcedFromFile: isSourcedFromFile
287
274
  )
288
275
  }
276
+ )
277
+ }
289
278
 
290
- // Run timers on non-continuous mode, as long as the audio source is the mic
291
- let shouldRunTimers = !options.continuous && !isSourcedFromFile
292
- let audioEngine = self.audioEngine
279
+ private func prepareFileRecognition(request: SFSpeechRecognitionRequest, url: URL) throws {
280
+ self.audioEngine = nil
293
281
 
294
- self.task = recognizer.recognitionTask(
295
- with: request,
296
- resultHandler: { [weak self] result, error in
297
- // Speech start event
298
- if result != nil && error == nil {
299
- Task { [weak self] in
300
- await self?.handleSpeechStart()
301
- }
302
- }
303
-
304
- // Handle the result
305
- self?.recognitionHandler(
306
- audioEngine: audioEngine,
307
- result: result,
308
- error: error,
309
- resultHandler: resultHandler,
310
- errorHandler: errorHandler,
311
- continuous: options.continuous,
312
- shouldRunTimers: shouldRunTimers,
313
- canEmitInterimResults: options.interimResults
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)
314
308
  )
315
- })
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
+ }
316
314
 
317
- if shouldRunTimers {
318
- invalidateAndScheduleTimer()
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()
319
321
  }
322
+ }
323
+ }
320
324
 
321
- // Emit the "start" event to indicate that speech recognition has started
322
- startHandler()
325
+ private func prepareMicrophoneRecognition(
326
+ request: SFSpeechRecognitionRequest,
327
+ options: SpeechRecognitionOptions
328
+ ) throws {
329
+ try Self.setupAudioSession(options.iosCategory)
330
+ self.audioEngine = AVAudioEngine()
323
331
 
324
- // If user has opted in to recording, emit an "audiostart" event with the path
325
- audioStartHandler(outputFileUrl?.path)
326
- } catch {
327
- errorHandler(error)
328
- reset(andEmitEnd: true)
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()
329
379
  }
330
380
  }
331
381
 
@@ -447,15 +497,10 @@ actor ExpoSpeechRecognizer: ObservableObject {
447
497
  }
448
498
 
449
499
  private static func prepareRequest(
450
- options: SpeechRecognitionOptions, recognizer: SFSpeechRecognizer
500
+ options: SpeechRecognitionOptions,
501
+ recognizer: SFSpeechRecognizer
451
502
  ) -> SFSpeechRecognitionRequest {
452
-
453
- let request: SFSpeechRecognitionRequest
454
- if let audioSource = options.audioSource {
455
- request = SFSpeechURLRecognitionRequest(url: URL(string: audioSource.uri)!)
456
- } else {
457
- request = SFSpeechAudioBufferRecognitionRequest()
458
- }
503
+ let request = SFSpeechAudioBufferRecognitionRequest()
459
504
 
460
505
  // We also force-enable partial results on non-continuous mode,
461
506
  // which will allow us to re-schedule timers when text is detected
@@ -694,7 +739,8 @@ actor ExpoSpeechRecognizer: ObservableObject {
694
739
  errorHandler: @escaping (Error) -> Void,
695
740
  continuous: Bool,
696
741
  shouldRunTimers: Bool,
697
- canEmitInterimResults: Bool
742
+ canEmitInterimResults: Bool,
743
+ isSourcedFromFile: Bool
698
744
  ) {
699
745
  // When a final result is returned, we should expect the task to be idle or stopping
700
746
  let receivedFinalResult = result?.isFinal ?? false
@@ -730,7 +776,9 @@ actor ExpoSpeechRecognizer: ObservableObject {
730
776
  }
731
777
  }
732
778
 
733
- if (receivedFinalLikeResult && !continuous) || receivedError || receivedFinalResult {
779
+ if receivedError || (receivedFinalLikeResult && !continuous && !isSourcedFromFile)
780
+ || receivedFinalResult
781
+ {
734
782
  Task { @MainActor in
735
783
  await reset()
736
784
  }
@@ -773,6 +821,36 @@ actor ExpoSpeechRecognizer: ObservableObject {
773
821
  }
774
822
  }
775
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
+ */
776
854
  }
777
855
 
778
856
  extension SFSpeechRecognizer {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-speech-recognition",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "Speech Recognition for React Native Expo projects",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",