【问题标题】:How to terminate speech recognition when user stop speaking with swift 5当用户停止使用 swift 5 说话时如何终止语音识别
【发布时间】:2019-12-06 18:34:53
【问题描述】:

我试图让用户说话并让用户说对了。我读了大约 20 篇关于语音识别的不同文章,几乎都是一样的。它会持续聆听用户 1 分钟或更长时间。我希望它在用户停止讲话时停止识别。我想抓住用户说的一个词/几个词。有什么东西限制了用户说话的时间吗?

我的代码块:

func recordAndRecognizeSpeech(){

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

    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(.record, mode: .measurement, options: .duckOthers)
        try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
    } catch {
        print("audioSession properties weren't set because of an error.")
    }

    recognitionRequest = SFSpeechAudioBufferRecognitionRequest()

    let node = audioEngine.inputNode
    guard let request = recognitionRequest else {
        fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
    }

    //request.shouldReportPartialResults = true

   // Setting requiresOnDeviceRecognition to false would use the Apple Cloud for speech recognition.
   if speechRecognizer?.supportsOnDeviceRecognition ?? false{
       request.requiresOnDeviceRecognition = true
   }

    guard let myRecognizer = SFSpeechRecognizer() else {
        // A recognizer is not supported for the current locale
        return
    }

    if !myRecognizer.isAvailable {
        // A recognizer is not available now
        return
    }

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

        if let result = result {

            DispatchQueue.main.async {

                  let bestString = result.bestTranscription.formattedString
                  print(bestString)

            }
        } else if let error = error {
            print(error)
            self.audioEngine.stop()
            node.removeTap(onBus: 0)

            self.recognitionRequest = nil
            self.recognitionTask = nil

            self.speakButton.isEnabled = true
        }
    })

    let recordingFormat = node.outputFormat(forBus: 0)
    node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat){buffer,_ in
        self.recognitionRequest!.append(buffer)
    }

    audioEngine.prepare()
    do {
        try audioEngine.start()
    } catch {
        return print(error)
    }
}

【问题讨论】:

    标签: ios swift speech-recognition


    【解决方案1】:

    您可以检查声音输入的功率,如果达到最小值,则启动计时器(如 3 秒),并在计时器触发后停止。

    var recorder: AVAudioRecorder?
    recorder.updateMeters()
    let dB = recorder.averagePower(forChannel: 0)
    

    【讨论】:

    • 感谢您的回答,但我可以不使用 AVAudioRecord 吗?
    猜你喜欢
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 2017-12-27
    • 2013-04-18
    相关资源
    最近更新 更多