Created
December 7, 2018 19:03
-
-
Save elizabethsiegle/50e4d7e56d30d887c1b8fae317908ed6 to your computer and use it in GitHub Desktop.
Complete startRecording() function for Travel the World via Speech Recognition and FlyoverKit in Swift Part 2
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
func startRecording() { | |
if recognitionTask != nil { //created when request kicked off by the recognizer. used to track progress of a transcription or cancel it | |
recognitionTask?.cancel() | |
recognitionTask = nil | |
} | |
let audioSession = AVAudioSession.sharedInstance() | |
do { | |
try audioSession.setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.record)), mode: .default) | |
try audioSession.setMode(AVAudioSession.Mode.measurement) | |
try audioSession.setActive(true, options: .notifyOthersOnDeactivation) | |
} catch { | |
print("Failed to setup audio session") | |
} | |
recognitionRequest = SFSpeechAudioBufferRecognitionRequest() //read from buffer | |
let inputNode = audioEngine.inputNode | |
guard let recognitionRequest = recognitionRequest else { | |
fatalError("Could not create request instance") | |
} | |
recognitionRequest.shouldReportPartialResults = true | |
recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest) { | |
res, err in | |
var isLast = false | |
if res != nil { //res contains transcription of a chunk of audio, corresponding to a single word usually | |
isLast = (res?.isFinal)! | |
} | |
if err != nil || isLast { | |
self.audioEngine.stop() | |
inputNode.removeTap(onBus: 0) | |
self.recognitionRequest = nil | |
self.recognitionTask = nil | |
self.locButton.isEnabled = true | |
let bestStr = res?.bestTranscription.formattedString | |
var inDict = self.locDict.contains { $0.key == bestStr} | |
if inDict { | |
self.placeLbl.text = bestStr | |
self.userInputLoc = self.locDict[bestStr!]! | |
} | |
else { | |
self.placeLbl.text = "can't find it in the dictionary" | |
self.userInputLoc = FlyoverAwesomePlace.centralParkNY | |
} | |
self.mapSetUp() | |
} | |
} | |
let format = inputNode.outputFormat(forBus: 0) | |
inputNode.installTap(onBus: 0, bufferSize: 1024, format: format) { | |
buffer, _ in | |
self.recognitionRequest?.append(buffer) | |
} | |
audioEngine.prepare() | |
do { | |
try audioEngine.start() | |
} catch { | |
print("Can't start the engine") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment