ios - 为什么第二次调用我的函数会触发两次? (Swift iOS 定时器/语音识别)

标签 ios swift speech-recognition speech speech-synthesis

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/

相关文章:

ios - 如何使用 WatchConnectivity 在我的 iOS 和 Watch 应用程序之间共享信息?

ios - 将已识别语音与已知文本进行比较的最佳方法

python - 是否可以在 Django 上使用 Python SpeechRecognition?

ios - 离开 View 并返回后,FetchedResult View 不会更新

ios - 如何将文件保存在 iOS 上的共享应用程序组中并从中读取

ios - 将 CNContact 作为 vCard 发送电子邮件

ios - 在堆栈 View 中点击按钮时未调用操作

oop - 一般而言,Swift 或 OOP 中元组的一些典型用例是什么?

arrays - 将 PFObject append 到数组,导致所有元素被替换(Swift、Parse)

java - Sphinx 4 配置 VoxForge