Stop speech recognition when user is finished spea

2019-03-18 13:28发布

How is Siri is able to determine when I'm finished speaking. The reason I would like to know is that I would like to implement similar functionality with Apple's Speech Recognition API with my app. Is this doable, or is the only way to know when the user has stopped speaking is via user input?

1条回答
我命由我不由天
2楼-- · 2019-03-18 13:59

You can use a timer, i had the same problem and I could not solve it with an elegant method.

fileprivate var timer:Timer?
func startRecordingTimer() {
    lastString = ""
    createTimerTimer(4)
}
func stopRecordingTimer() {
    timer?.invalidate()
    timer = nil
}
fileprivate func whileRecordingTimer() {
    createTimerTimer(2)
}
fileprivate var lastString = ""
func createTimerTimer(_ interval:Double) {
    OperationQueue.main.addOperation({[unowned self] in
        self.timer?.invalidate()
        self.timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { (_) in
            self.timer?.invalidate()
            if(self.lastString.characters.count > 0){
                //DO SOMETHING
            }else{
                self.whileRecordingTimer()
            }
        }
    })
}

and in SFSpeechRecognitionTaskDelegate

public func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didHypothesizeTranscription transcription: SFTranscription) {
    let result = transcription.formattedString
    lastString = result
}
查看更多
登录 后发表回答