Skip to content

Instantly share code, notes, and snippets.

@gaelfoppolo
Created September 25, 2016 22:44
Show Gist options
  • Save gaelfoppolo/6faa3395a3caaf1e602a782b4697bd36 to your computer and use it in GitHub Desktop.
Save gaelfoppolo/6faa3395a3caaf1e602a782b4697bd36 to your computer and use it in GitHub Desktop.
private func startRecording() throws {
// 1
if let recognitionTask = self.recognitionTask {
recognitionTask.cancel()
self.recognitionTask = nil
}
// 2
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(AVAudioSessionCategoryRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") }
// 3
self.recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
guard let recognitionRequest = recognitionRequest else { fatalError("Unable to created a SFSpeechAudioBufferRecognitionRequest object") }
self.recognitionRequest.shouldReportPartialResults = true
// 4
self.recognitionTask = self.speechRecognizer.recognitionTask(with: recognitionRequest) { result, error in
var isFinal = false
// 5
if let result = result {
self.textView.text = result.bestTranscription.formattedString
isFinal = result.isFinal
}
// 6
if error != nil || isFinal {
self.audioEngine.stop()
inputNode.removeTap(onBus: 0)
self.recognitionRequest = nil
self.recognitionTask = nil
self.recordButton.isEnabled = true
}
}
// 7
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