Swift: stop speech recognition after x seconds of silence
This is what ended up working for me:
func restartSpeechTimer() { timer?.invalidate() timer = Timer.scheduledTimer(withTimeInterval: 1.5, repeats: false, block: { (timer) in // Do whatever needs to be done when the timer expires })}
And inside the recognition task:
var isFinal = falseif letresult = result { // do something with the result isFinal = result.isFinal}if iFinal { self.stopRecording()}else if error == nil { self.restartSpeechTimer()}
I had the same issue until now. Checked your question and I suppose the code below helps you achieve the same thing I did.
recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in var isFinal = false if result != nil { self.inputTextView.text = result?.bestTranscription.formattedString isFinal = (result?.isFinal)! } if let timer = self.detectionTimer, timer.isValid { if isFinal { self.inputTextView.text = "" self.textViewDidChange(self.inputTextView) self.detectionTimer?.invalidate() } } else { self.detectionTimer = Timer.scheduledTimer(withTimeInterval: 1.5, repeats: false, block: { (timer) in self.handleSend() isFinal = true timer.invalidate() }) } })
This checks if input wasn't received for 1.5 seconds.