Last active
February 8, 2017 19:28
-
-
Save 2075/49e7be9b2f7796d4f7621a0a131ed49f to your computer and use it in GitHub Desktop.
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
@IBAction func audioButtonPressed(_ sender: Any) { | |
if isRecording { | |
stopRecording() | |
delegate?.speechRecognitionComplete(query: query) | |
audioButton.backgroundColor = UIColor.red | |
isRecording = false | |
} else { | |
startRecording() | |
audioButton.backgroundColor = UIColor.green | |
isRecording = true | |
} | |
} | |
func stopRecording() { | |
audioEngine.stop() | |
audioEngine.inputNode?.removeTap(onBus: 0) | |
recognitionRequest = nil | |
recognitionTask = nil | |
} | |
func startRecording() { | |
recognitionRequest = SFSpeechAudioBufferRecognitionRequest() | |
guard let recognitionRequest = recognitionRequest else { | |
return | |
} | |
recognitionRequest.shouldReportPartialResults = true | |
recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in | |
var isFinal = false | |
if result != nil { | |
self.query = result?.bestTranscription.formattedString | |
self.audioTextField.text = self.query | |
isFinal = (result?.isFinal)! | |
} | |
if error != nil || isFinal { | |
self.stopRecording() | |
} | |
}) | |
let audioSession = AVAudioSession.sharedInstance() | |
do { | |
try audioSession.setCategory(AVAudioSessionCategoryRecord) | |
try audioSession.setMode(AVAudioSessionModeMeasurement) | |
try audioSession.setActive(true, with: .notifyOthersOnDeactivation) | |
} catch { | |
print("the audio session isn't configured correctly") | |
} | |
let recordingFormat = audioEngine.inputNode?.outputFormat(forBus: 0) | |
audioEngine.inputNode?.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, time) in | |
self.recognitionRequest?.append(buffer) | |
} | |
audioEngine.prepare() | |
do { | |
try audioEngine.start() | |
audioTextField.text = "How may I help you" | |
} catch { | |
print("audio engine failed to start") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment