Swift SFSpeechRecognizer没有工作两次

时间:2017-02-03 09:10:23

标签: ios swift speech-recognition text-to-speech

这是我第一次在Swift中使用SFSpeechRecognizer,但其中一项功能无效。当我按下按钮audioButtonPressed时,似乎开始识别正常,再次按下它会停止它。当我再次尝试按它再次开始识别时,识别不起作用,并留下空白文本视图。我该怎么做?

这是我的代码

@IBAction func audioButtonPressed(_ sender: Any) {
    if isRecording {
        stopRecording()
        delegate?.speechRecognitionComplete(query: query)
        audioButton.backgroundColor = UIColor.red
        isRecording = false
    } else {
        startRecording()
        audioButton.backgroundColor = UIColor.green
        isRecording = true
    }
}

func stopRecording() {
    audioEngine.stop()
    audioEngine.inputNode?.removeTap(onBus: 0)
    recognitionRequest = nil
    recognitionTask = nil
}

func startRecording() {
    recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
    guard let recognitionRequest = recognitionRequest else {
        return
    }
    recognitionRequest.shouldReportPartialResults = true
    recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
        var isFinal = false
        if result != nil {
            self.query = result?.bestTranscription.formattedString
            self.audioTextField.text = self.query
            isFinal = (result?.isFinal)!
        }
        if error != nil || isFinal {
            self.stopRecording()
        }
    })
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
        try audioSession.setMode(AVAudioSessionModeMeasurement)
        try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
    } catch {
        print("the audio session isn't configured correctly")
    }
    let recordingFormat = audioEngine.inputNode?.outputFormat(forBus: 0)
    audioEngine.inputNode?.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, time) in
        self.recognitionRequest?.append(buffer)
    }
    audioEngine.prepare()
    do {
        try audioEngine.start()
        audioTextField.text = "How may I help you"
    } catch {
        print("audio engine failed to start")
    }
}

当我第一次按下audiobutton时,开始录音被调用并且它完美地工作,再次按下它停止录音被调用并且工作正常,但再次按下不会使识别重新开始......想法?

1 个答案:

答案 0 :(得分:2)

我认为你在stopRecording函数中释放任务之前缺少recognitionTask.cancel()