self.adaResponseApi
在最后一次录制的语音输入后计时器达到 1.5 秒时运行两次。它应该只运行一次。
它是专门从 1.5 间隔实例化开始运行的,而不是从第一个实例化开始运行的,第一次实例化是在用户专门停止语音输入时触发的。
recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
if result != nil {
self.textView.text = result?.bestTranscription.formattedString
self.isFinal = (result?.isFinal)!
}
if let timer = self.detectionTimer, (timer.isValid) {
if self.isFinal! {
self.detectionTimer?.invalidate()
self.adaResponseApi()
self.isFinal = true
}
} else { // if self.isFinal == false
self.detectionTimer = Timer.scheduledTimer(withTimeInterval: 1.5, repeats: false, block: { timer in
self.adaResponseApi() // This call gets triggered twice and for the life of me I can't figure out why.
timer.invalidate()
self.isFinal = true
})
}
})
最佳答案
好吧...我假设请求的 shouldReportPartialResults
设置为 true
(默认值)。
recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { [weak self] (result, error) in
// [weak self] to stop memory leaks
guard let result = result else {
// no result means probably an error, you should report that to your user
return
}
// display the most accurate transcription (partial or final)
self?.textView.text = result.bestTranscription.formattedString
// invalidate timer
// result is final (and so should invalidate timer)
// or result is partial (and so will create new timer ... and invalidate this one)
self?.detectionTimer?.invalidate()
if result.isFinal {
// we have a final result... use it
self?.adaResponseApi()
} else {
// create timer for if the next response times out
self?.detectionTimer = Timer.scheduledTimer(withTimeInterval: 1.5, repeats: false) { [weak self] timer in
self?.adaResponseApi()
}
}
}
我想我会这样做......
我不是 100% 确定你的计时器是用来做什么的,所以我假设它在那里以防识别器没有快速返回响应,这样我们就可以回退到最近的 partial
结果?
我也不认为我们应该需要存储 result.isFinal
的值。如果确实需要,则可以将其添加到 self?.textView.text = result.bestTranscription.formattedString
之后的行。
关于ios - 为什么第二次调用我的函数会触发两次? (Swift iOS 定时器/语音识别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49753234/