1- import Speech
21import Foundation
32import Observation
3+ import Speech
44
55@Observable
66class SpeechRecognitionService {
77 private let speechRecognizer = SFSpeechRecognizer ( locale: Locale ( identifier: " en-US " ) )
88 private var recognitionRequest : SFSpeechAudioBufferRecognitionRequest ?
99 private var recognitionTask : SFSpeechRecognitionTask ?
1010 private let audioEngine = AVAudioEngine ( )
11-
11+
1212 var isRecording = false
1313 var onTranscript : ( ( String ) -> Void ) ?
1414 var onError : ( ( Error ) -> Void ) ?
15-
15+
1616 init ( ) {
1717 requestAuthorization ( )
1818 }
19-
19+
2020 private func requestAuthorization( ) {
2121 SFSpeechRecognizer . requestAuthorization { status in
2222 DispatchQueue . main. async {
@@ -32,48 +32,48 @@ class SpeechRecognitionService {
3232 }
3333 }
3434 }
35-
35+
3636 func startRecording( ) throws {
3737 // Cancel any ongoing task
3838 recognitionTask? . cancel ( )
3939 recognitionTask = nil
40-
40+
4141 #if !os(macOS)
42- // Configure audio session
43- let audioSession = AVAudioSession . sharedInstance ( )
44- try audioSession. setCategory ( . record, mode: . measurement, options: . duckOthers)
45- try audioSession. setActive ( true , options: . notifyOthersOnDeactivation)
42+ // Configure audio session
43+ let audioSession = AVAudioSession . sharedInstance ( )
44+ try audioSession. setCategory ( . record, mode: . measurement, options: . duckOthers)
45+ try audioSession. setActive ( true , options: . notifyOthersOnDeactivation)
4646 #endif
47-
47+
4848 recognitionRequest = SFSpeechAudioBufferRecognitionRequest ( )
49-
49+
5050 guard let recognitionRequest = recognitionRequest else { return }
51-
51+
5252 let inputNode = audioEngine. inputNode
5353 recognitionRequest. shouldReportPartialResults = true
54-
54+
5555 recognitionTask = speechRecognizer? . recognitionTask ( with: recognitionRequest) { [ weak self] result, error in
5656 if let error = error {
5757 self ? . onError ? ( error)
5858 self ? . stopRecording ( )
5959 return
6060 }
61-
61+
6262 if let result = result {
6363 self ? . onTranscript ? ( result. bestTranscription. formattedString)
6464 }
6565 }
66-
66+
6767 let recordingFormat = inputNode. outputFormat ( forBus: 0 )
6868 inputNode. installTap ( onBus: 0 , bufferSize: 1024 , format: recordingFormat) { buffer, _ in
6969 recognitionRequest. append ( buffer)
7070 }
71-
71+
7272 audioEngine. prepare ( )
7373 try audioEngine. start ( )
7474 isRecording = true
7575 }
76-
76+
7777 func stopRecording( ) {
7878 audioEngine. stop ( )
7979 audioEngine. inputNode. removeTap ( onBus: 0 )
@@ -83,4 +83,4 @@ class SpeechRecognitionService {
8383 recognitionTask = nil
8484 isRecording = false
8585 }
86- }
86+ }
0 commit comments