如何在Swift中即使用户不说话SFSpeechRecognizer,语音识别也能强制我的应用程序收听

问题描述

即使用户停止讲话,我也一直试图保持语音识别功能打开。

您可以在下面看到我的代码

如果我按如下所示设置计时器

Timer.scheduledTimer(timeInterval: 10.0,target: self,selector: #selector(StepsViewController.startListening),userInfo: nil,repeats: true)

出现此错误 Thread 1: "required condition is false: nullptr == Tap()"

我将不胜感激。 谢谢。

func startListening() {
    isListening = true
    updateMicButtonStyletoListening ()
    
    do {
        try session.setCategory(AVAudioSession.Category.playAndRecord)
        try session.setMode(AVAudioSession.Mode.default)
        //try audioSession.setMode(AVAudioSessionModeMeasurement)
        try session.setActive(true,options: .notifyOthersOnDeactivation)
        try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
    } catch {
        
        print("audioSession properties weren't set because of an error.")
    }
    
    
    
    let node = audioEngine.inputNode
    let recordingFormat = node.outputFormat(forBus: 0)
    node.installTap(onBus: 0,bufferSize: 1024,format: recordingFormat) { buffer,_ in
        
        self.request.append(buffer)
    }
    
    audioEngine.prepare()
    do {
        try audioEngine.start()
    } catch {
        return print(error)
    }
    guard let myRecognizer = SFSpeechRecognizer() else {
        return
    }
    if !myRecognizer.isAvailable {
        return
    }
    recognitionTask = speechRecognizer.recognitionTask(with: request,resultHandler: { [self] result,error in
        if let result = result {
            let bestString = result.bestTranscription.formattedString
            
            var lastString : String = ""
            for segment in result.bestTranscription.segments {
                let indexTo = bestString.index(bestString.startIndex,offsetBy: segment.substringRange.location)
                lastString = bestString.substring(from: indexTo)
                voiceCommand = lastString
                takeActionBasedOnCommand()
                print(voiceCommand)
            }
        } else if let error = error {
            print(error)
        }
    })
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)