2017-07-14 87 views
1

我找過一個解決方案,但是我看到的所有解決方案都很混亂,所以我想我會創建一個新問題。Swift:在沉默x秒後停止語音識別

我正在使用語音庫,並且我希望識別任務在2秒後停止,而無需用戶輸入。我知道我想用一個計時器,但我很難弄清楚在哪裏放置它以及如何更新它。

當按下記錄按鈕時,我開始計時,當按下停止記錄按鈕時,我使其無效。

但我在哪裏檢查用戶是否添加了新的輸入?我正在考慮保存最後一個轉錄並將其與下一個轉錄進行比較:當它們不同時,重置計時器。

這裏是我的代碼如下所示:

recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { result, error in 
    var isFinal = false 

    if let result = result { 
     self.textView.text = result.bestTranscription.formattedString 
    // Should I compare the result here to see if it changed? 
     isFinal = result.isFinal 
    } 

    // Or should I do it here? In what order is this code even running? 

    if error != nil || isFinal { 
     self.result = self.textView.text 

     self.audioEngine.stop() 
     inputNode.removeTap(onBus: 0) 

     self.recognitionRequest = nil 
     self.recognitionTask = nil 

     self.recordButton.isEnabled = true 
     self.recordButton.setTitle("Start Recording", for: []) 
    } 
} 

回答

0

我有同樣的問題到現在爲止。檢查你的問題,我想下面的代碼可以幫助你實現我做的同樣的事情。

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() 
      }) 
     } 

    }) 

這會檢查輸入是否在1.5秒內未收到。

0

這是結束了,我的工作:

func restartSpeechTimer() { 
    timer?.invalidate() 
    timer = Timer.shceduleTimer(withTimeInterval: 1.5, repeats: false, block: { (timer) in 
     // Do whatever needs to be done when the timer expires 
    }) 
} 

和識別任務中:

var isFinal = false 
if letresult = result { 
    // do something with the result 
    isFinal = result.isFinal 
} 
if iFinal { 
    self.stopRecording() 
} 
else if error == nil { 
    self.restartSpeechTimer() 
}