不间断的iOS语音识别?

时间:2019-02-13 06:23:34

标签: ios swift4 speech-to-text speech

在我的一个应用程序中,我正在使用Speech框架将用户的语音转换为Text。

基本上,我希望我的应用程序可以通过一些命令免提使用。

因此,Apple每小时只能处理1000个请求,而SFSpeechRecognitionTask仅持续大约1分钟。

我希望SFSpeechRecognitionTask应该活着并保持识别声音。 那么,使用代码的最佳方法是什么。电池电量是否过多?如果我每隔1分钟重新启动SFSpeechRecognitionTask一次?

我已经完成了如下代码来开始检测语音,并且将在1分钟后停止。

如果有办法实现,请帮助我。

func startRecording() {

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

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

        recognitionRequest = SFSpeechAudioBufferRecognitionRequest()

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

        guard let recognitionRequest = recognitionRequest else {
            fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
        }

        recognitionRequest.shouldReportPartialResults = true

        recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in

            var isFinal = false

            if result != nil {

                if self.speechTimer != nil
                {
                    if (self.speechTimer?.isValid)!
                    {
                        self.speechTimer?.invalidate()
                    }
                    self.speechTimer = nil;
                }
                print(result?.bestTranscription.formattedString as Any)

                self.speechTimer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false, block: { (timer) in
                    print("Recognition task restart")
                })

                isFinal = (result?.isFinal)!
                if isFinal {
                    print("Final String: \(result?.bestTranscription.formattedString ?? "No string")")
                }
            }
        })

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

        audioEngine.prepare()

        do {
            try audioEngine.start()
        } catch {
            print("audioEngine couldn't start because of an error.")
        }
    }

0 个答案:

没有答案