我正在使用Swift中的语音识别,并且在取消SFSpeechRecognitionTask
时遇到问题。
我已经实现了以下逻辑:
recognitionTask
用于它)。所以我为此目的使用stopRecording()
函数。此功能正常。recognitionTask
。所以我需要recognitionTask
立即停止完成处理程序并返回错误或结果。为此,我写了cancelTask()
。我已尝试过此功能的不同变体,但不起作用。问题是,当app运行缓慢的互联网连接(例如边缘)时,我总是在一段时间后完成。 我在recognitionTask.isCanceled
之后检查了recognitionTask?.cancel()
,此属性始终为false
。任何想法为什么这不起作用?
func startRecording() throws {
guard speechRecogniser.isAvailable else {
// Speech recognition is unavailable, so do not attempt to start.
return
}
if let recognitionTask = recognitionTask {
// We have a recognition task still running, so cancel it before starting a new one.
recognitionTask.cancel()
self.recognitionTask = nil
}
guard SFSpeechRecognizer.authorizationStatus() == .authorized else {
SFSpeechRecognizer.requestAuthorization({ _ in })
return
}
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(AVAudioSessionCategoryRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
let inputNode = audioEngine.inputNode
guard let recognitionRequest = recognitionRequest else {
throw SpeechControllerError.noAudioInput
}
recognitionTask = speechRecogniser.recognitionTask(with: recognitionRequest) { [unowned self] result, error in
if let result = result {
self.delegate?.speechController(self, didRecogniseText: result.bestTranscription.formattedString)
}
if result?.isFinal ?? (error != nil) {
inputNode.removeTap(onBus: SpeechController.inputNodeBus)
}
}
let recordingFormat = inputNode.outputFormat(forBus: SpeechController.inputNodeBus)
inputNode.installTap(onBus: SpeechController.inputNodeBus, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
self.recognitionRequest?.append(buffer)
}
audioEngine.prepare()
try audioEngine.start()
}
/// Ends the current speech recording session.
func stopRecording() {
audioEngine.stop()
recognitionRequest?.endAudio()
}
func cancelTask() {
audioEngine.inputNode.removeTap(onBus: 0)
audioEngine.stop()
recognitionRequest?.endAudio()
recognitionTask?.cancel()
recognitionTask = nil
speechRecognizer = nil
recognitionRequest = nil
}