expo-speech-recognition 0.2.25 → 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.
@@ -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 isSourcedFromFile {
230
- // If we're doing file-based recognition we don't need to create an audio engine
231
- 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)!)
232
224
  } else {
233
- // Set up the audio session to get the correct audio format
234
- try Self.setupAudioSession(options.iosCategory)
235
-
236
- self.audioEngine = AVAudioEngine()
225
+ try prepareMicrophoneRecognition(request: request, options: options)
226
+ }
237
227
 
238
- guard let audioEngine = self.audioEngine else {
239
- print("expo-speech-recognition: ERROR - Failed to create AVAudioEngine")
240
- throw RecognizerError.invalidAudioSource
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
- let inputNode = audioEngine.inputNode
244
- // Note: accessing `inputNode.outputFormat(forBus: 0)` may crash the thread with the error:
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
- // Check if the microphone is busy
250
- guard !Self.audioInputIsBusy(audioFormat) else {
251
- print(
252
- "expo-speech-recognition: ERROR - input is busy \(audioFormat)"
253
- )
254
- throw RecognizerError.audioInputBusy
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
- let mixerNode = AVAudioMixerNode()
258
- audioEngine.attach(mixerNode)
259
- audioEngine.connect(inputNode, to: mixerNode, format: audioFormat)
260
-
261
- // Feature: file recording
262
- if options.recordingOptions?.persist == true {
263
- guard
264
- let fileAudioFormat = Self.getFileAudioFormat(
265
- options: options,
266
- engine: audioEngine
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
- // Set up audio recording & sink to recognizer/file
284
- try Self.prepareEngine(
261
+ self.task = recognizer.recognitionTask(
262
+ with: request,
263
+ resultHandler: { [weak self] result, error in
264
+ self?.recognitionHandler(
285
265
  audioEngine: audioEngine,
286
- mixerNode: mixerNode,
287
- options: options,
288
- request: request,
289
- audioFileRef: self.audioFileRef,
290
- volumeChangeHandler: { volume in
291
- Task { @MainActor in
292
- self.volumeChangeHandler?(volume)
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
- // Run timers on non-continuous mode, as long as the audio source is the mic
299
- let shouldRunTimers = !options.continuous && !isSourcedFromFile
300
- let audioEngine = self.audioEngine
279
+ private func prepareFileRecognition(request: SFSpeechRecognitionRequest, url: URL) throws {
280
+ self.audioEngine = nil
301
281
 
302
- self.task = recognizer.recognitionTask(
303
- with: request,
304
- resultHandler: { [weak self] result, error in
305
- // Speech start event
306
- if result != nil && error == nil {
307
- Task { [weak self] in
308
- await self?.handleSpeechStart()
309
- }
310
- }
311
-
312
- // Handle the result
313
- self?.recognitionHandler(
314
- audioEngine: audioEngine,
315
- result: result,
316
- error: error,
317
- resultHandler: resultHandler,
318
- errorHandler: errorHandler,
319
- continuous: options.continuous,
320
- shouldRunTimers: shouldRunTimers,
321
- 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)
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
- if shouldRunTimers {
326
- 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()
327
321
  }
322
+ }
323
+ }
328
324
 
329
- // Emit the "start" event to indicate that speech recognition has started
330
- startHandler()
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
- // If user has opted in to recording, emit an "audiostart" event with the path
333
- audioStartHandler(outputFileUrl?.path)
334
- } catch {
335
- errorHandler(error)
336
- 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()
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, recognizer: SFSpeechRecognizer
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) || receivedError || receivedFinalResult {
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,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-speech-recognition",
3
- "version": "0.2.25",
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",
@@ -557,14 +557,42 @@ export interface ExpoSpeechRecognitionModuleType extends NativeModule {
557
557
  /**
558
558
  * Presents a dialog to the user to request permissions for using speech recognition and the microphone.
559
559
  *
560
- * For iOS, once a user has granted (or denied) location permissions by responding to the original permission request dialog,
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,
561
564
  * the only way that the permissions can be changed is by the user themselves using the device settings app.
562
565
  */
563
566
  requestPermissionsAsync(): Promise<PermissionResponse>;
564
567
  /**
565
- * Returns the current permission status for the microphone and speech recognition.
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.
566
571
  */
567
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>;
568
596
  /**
569
597
  * Returns an array of locales supported by the speech recognizer.
570
598
  *
@@ -2,6 +2,7 @@ import type { PermissionResponse } from "expo-modules-core";
2
2
  import type {
3
3
  ExpoSpeechRecognitionModuleType,
4
4
  ExpoSpeechRecognitionNativeEventMap,
5
+ ExpoSpeechRecognitionResultSegment,
5
6
  } from "./ExpoSpeechRecognitionModule.types";
6
7
 
7
8
  let _speechRecognitionRef: SpeechRecognition | null = null;
@@ -51,15 +52,15 @@ export const ExpoSpeechRecognitionModule: ExpoSpeechRecognitionModuleType = {
51
52
  status: "granted",
52
53
  } as PermissionResponse);
53
54
  },
54
- getPermissionsAsync: () => {
55
+ getPermissionsAsync() {
55
56
  console.warn(
56
- "getPermissionsAsync is not supported on web. Returning a denied permission response.",
57
+ "getPermissionsAsync is not supported on web. Returning a granted permission response.",
57
58
  );
58
59
  return Promise.resolve({
59
- granted: false,
60
+ granted: true,
60
61
  canAskAgain: false,
61
62
  expires: "never",
62
- status: "denied",
63
+ status: "granted",
63
64
  } as PermissionResponse);
64
65
  },
65
66
  getSupportedLocales: async () => {
@@ -132,6 +133,50 @@ export const ExpoSpeechRecognitionModule: ExpoSpeechRecognitionModuleType = {
132
133
 
133
134
  return hasSpeechRecognitionAPI;
134
135
  },
136
+ getMicrophonePermissionsAsync() {
137
+ console.warn(
138
+ "getMicrophonePermissionsAsync is not supported on web. Returning a granted permission response.",
139
+ );
140
+ return Promise.resolve({
141
+ granted: true,
142
+ canAskAgain: false,
143
+ expires: "never",
144
+ status: "granted",
145
+ } as PermissionResponse);
146
+ },
147
+ requestMicrophonePermissionsAsync() {
148
+ console.warn(
149
+ "requestMicrophonePermissionsAsync is not supported on web. Returning a granted permission response.",
150
+ );
151
+ return Promise.resolve({
152
+ granted: true,
153
+ canAskAgain: false,
154
+ expires: "never",
155
+ status: "granted",
156
+ } as PermissionResponse);
157
+ },
158
+ getSpeechRecognizerPermissionsAsync() {
159
+ console.warn(
160
+ "getSpeechRecognizerPermissionsAsync is not supported on web. Returning a granted permission response.",
161
+ );
162
+ return Promise.resolve({
163
+ granted: true,
164
+ canAskAgain: false,
165
+ expires: "never",
166
+ status: "granted",
167
+ } as PermissionResponse);
168
+ },
169
+ requestSpeechRecognizerPermissionsAsync() {
170
+ console.warn(
171
+ "requestSpeechRecognizerPermissionsAsync is not supported on web. Returning a granted permission response.",
172
+ );
173
+ return Promise.resolve({
174
+ granted: true,
175
+ canAskAgain: false,
176
+ expires: "never",
177
+ status: "granted",
178
+ } as PermissionResponse);
179
+ },
135
180
  };
136
181
 
137
182
  /**
@@ -147,22 +192,63 @@ const webToNativeEventMap: {
147
192
  end: (ev) => null,
148
193
  error: (ev) => ({ error: ev.error, message: ev.message }),
149
194
  nomatch: (ev) => null,
150
- result: (ev) => {
151
- const nativeResults: ExpoSpeechRecognitionNativeEventMap["result"]["results"] =
152
- [];
195
+ result: (ev): ExpoSpeechRecognitionNativeEventMap["result"] => {
196
+ const isFinal = Boolean(ev.results[ev.resultIndex]?.isFinal);
197
+
198
+ if (isFinal) {
199
+ const results: ExpoSpeechRecognitionNativeEventMap["result"]["results"] =
200
+ [];
201
+
202
+ for (let i = 0; i < ev.results[ev.resultIndex].length; i++) {
203
+ const result = ev.results[ev.resultIndex][i];
204
+ results.push({
205
+ transcript: result.transcript,
206
+ confidence: result.confidence,
207
+ segments: [],
208
+ });
209
+ }
210
+ return {
211
+ isFinal: true,
212
+ results,
213
+ };
214
+ }
153
215
 
154
- for (let i = 0; i < ev.results[ev.resultIndex].length; i++) {
155
- const result = ev.results[ev.resultIndex][i];
156
- nativeResults.push({
157
- transcript: result.transcript,
158
- confidence: result.confidence,
159
- segments: [],
160
- });
216
+ // Interim results: Append to the transcript
217
+ let transcript = "";
218
+ const segments: ExpoSpeechRecognitionResultSegment[] = [];
219
+
220
+ for (let i = ev.resultIndex; i < ev.results.length; i++) {
221
+ const resultList = ev.results[i];
222
+
223
+ for (let j = 0; j < resultList.length; j++) {
224
+ const result = resultList[j];
225
+ if (!result) {
226
+ continue;
227
+ }
228
+ segments.push({
229
+ confidence: result.confidence,
230
+ segment: result.transcript,
231
+ startTimeMillis: 0,
232
+ endTimeMillis: 0,
233
+ });
234
+
235
+ if (!isFinal) {
236
+ transcript += result.transcript;
237
+ }
238
+ }
161
239
  }
162
240
 
163
241
  return {
164
- isFinal: Boolean(ev.results[ev.resultIndex]?.isFinal),
165
- results: nativeResults,
242
+ isFinal: false,
243
+ results: [
244
+ {
245
+ transcript,
246
+ confidence:
247
+ segments.reduce((acc, curr) => acc + curr.confidence, 0) /
248
+ segments.length,
249
+ segments,
250
+ },
251
+ ],
166
252
  };
167
253
  },
168
254
  soundstart: (ev) => null,
@@ -1,7 +1,6 @@
1
- import type { Subscription } from "expo-modules-core";
2
-
3
1
  // Import the native module. On web, it will be resolved to ExpoSpeechRecognition.web.ts
4
2
  // and on native platforms to ExpoSpeechRecognition.ts
3
+ import type { Subscription } from "expo-modules-core";
5
4
  import {
6
5
  ExpoSpeechRecognitionModule,
7
6
  ExpoSpeechRecognitionModuleEmitter,