在继续转换语音框架ios时崩溃10

时间:2017-08-31 13:40:29

标签: ios swift3 speech-recognition

我在继续与speech.framework交谈时遇到崩溃,并且在AVAudio引擎失败的情况下获得NULL。

  

***因未捕获的异常'com.apple.coreaudio.avfaudio'终止应用程序,原因:'必需条件为false:   nullptr == Tap()'

这是因为在某些情况下我的AudioEngine获得null

这是我的StartRecording功能代码:

func startRecording(){

    if recognizationTask != nil{
        recognizationTask?.cancel()
        recognizationTask = nil
    }

    let audioSession = AVAudioSession.sharedInstance()
    do{
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
        try audioSession.setMode(AVAudioSessionModeSpokenAudio)
        try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
    } catch {
        print("Audion session properies weren't set because of an error.")
    }

    recognizationRequest = SFSpeechAudioBufferRecognitionRequest()

    guard let inputNode = audioEngine.inputNode as AVAudioInputNode? else {
        fatalError("Audio engine has no input node")
    }

    guard let recognizationRequest = recognizationRequest else {
        fatalError("Unable to create an SFSpeechAudioBufferRecognizationRequest object.")
    }

    recognizationRequest.shouldReportPartialResults = true

    recognizationTask = speechRecognizer?.recognitionTask(with: recognizationRequest, resultHandler: { (result, error) in
        var isFinal = false

        if result != nil{
            self.txtViewSiriDetecation.text = result?.bestTranscription.formattedString
            isFinal = (result?.isFinal)!
        }

        if error != nil || isFinal {
            self.audioEngine.stop()
            inputNode.removeTap(onBus:0)

            self.recognizationRequest = nil
            self.recognizationTask = nil

            self.btnSiri.isEnabled = true

        }


    })

    let recordingFormat = inputNode.outputFormat(forBus: 0)
    inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
        self.recognizationRequest?.append(buffer)
    }

    audioEngine.prepare()

    do {
        try audioEngine.start()
    } catch {
        print("audio engine couldn't start b'cus of an error.")
    }

    txtViewSiriDetecation.text = "Say something, I'm listening!"

}

如何克服这种获取NULL的情况?

有人指导我吗?

提前致谢!

2 个答案:

答案 0 :(得分:0)

正在传递installTap的非零格式。仅当连接到未连接到另一个节点的输出总线时,才应这样做。否则将导致错误。指定总线上的分接头和连接格式(如果为非零)应相同。否则,后面的操作将覆盖任何先前设置的格式。

答案 1 :(得分:0)

我也遇到了这个问题,添加了audioEngine.inputNode.removeTap(onBus:0)为我修复了它。

  fileprivate func stopRecording() {
      recordingMic.isHidden = true
      audioEngine.stop()
      audioEngine.inputNode.removeTap(onBus: 0)
      recognitionRequest?.endAudio()
      recognitionTask?.cancel()

      self.detectSpeechButton.isEnabled = true
      self.detectSpeechButton.setTitle("Detect Speech", for: .normal)
      recordingMic.isHidden = true
      self.textView.isHidden = false
  }