Created
October 9, 2019 16:59
-
-
Save dbolella/fa072a99b1f521300a2ac6a83389c842 to your computer and use it in GitHub Desktop.
Start Recording Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Thanks to https://developer.apple.com/documentation/speech/recognizing_speech_in_live_audio | |
func startRecording() throws { | |
// Cancel the previous task if it's running. | |
recognitionTask?.cancel() | |
self.recognitionTask = nil | |
// Configure the audio session for the app. | |
let audioSession = AVAudioSession.sharedInstance() | |
try audioSession.setCategory(.record, mode: .measurement, options: .duckOthers) | |
try audioSession.setActive(true, options: .notifyOthersOnDeactivation) | |
let inputNode = audioEngine.inputNode | |
// Create and configure the speech recognition request. | |
recognitionRequest = SFSpeechAudioBufferRecognitionRequest() | |
guard let recognitionRequest = recognitionRequest else { fatalError("Unable to create a SFSpeechAudioBufferRecognitionRequest object") } | |
recognitionRequest.shouldReportPartialResults = true | |
// Keep speech recognition data on device | |
if #available(iOS 13, *) { | |
recognitionRequest.requiresOnDeviceRecognition = false | |
} | |
// Create a recognition task for the speech recognition session. | |
// Keep a reference to the task so that it can be canceled. | |
recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { result, error in | |
var isFinal = false | |
if let result = result { | |
// ***We will update State here!*** | |
// ??? = result.bestTranscription.formattedString | |
isFinal = result.isFinal | |
print("Text \(result.bestTranscription.formattedString)") | |
} | |
if error != nil || isFinal { | |
// Stop recognizing speech if there is a problem. | |
self.audioEngine.stop() | |
inputNode.removeTap(onBus: 0) | |
self.recognitionRequest = nil | |
self.recognitionTask = nil | |
} | |
} | |
// Configure the microphone input. | |
let recordingFormat = inputNode.outputFormat(forBus: 0) | |
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in | |
self.recognitionRequest?.append(buffer) | |
} | |
audioEngine.prepare() | |
try audioEngine.start() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment