首页 > 解决方案 > 语音识别器不返回答案

问题描述

我正在关注有关 iOS 10 语音识别 API 的一些教程(https://code.tutsplus.com/tutorials/using-the-speech-recognition-api-in-ios-10--cms-28032?ec_unit=translation- info-language)和我的版本只是不工作。语音输入没有文本响应。我按照教程进行了操作,但必须进行一些更改(显然较新版本的 Swift 不接受与教程中完全相同的某些代码行)。你们能给我一些关于它如何以及为什么不起作用的想法吗?

这是我正在运行的方法:

func startRecording() {
    // Setup audio engine and speech recognizer
    let node = audioEngine.inputNode
    let recordingFormat = node.outputFormat(forBus: 0)
    node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
        self.request.append(buffer)
    }

    // Prepare and start recording
    audioEngine.prepare()
    do {
        try audioEngine.start()
        self.status = .recognizing
    } catch {
        return print(error)
    }

    // Analyze the speech
    recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
        if let result = result {
            self.tview.text = result.bestTranscription.formattedString
            NSLog(result.bestTranscription.formattedString)
        } else if let error = error {
            print(error)
            NSLog(error.localizedDescription)
        }
    })
}

调试时,speechRecognizer 和 recognitionTask 都没有 nil 值。

这就是我在 ViewController 上定义变量的方式:

let audioEngine = AVAudioEngine()
let speechRecognizer: SFSpeechRecognizer? = SFSpeechRecognizer()
let request = SFSpeechAudioBufferRecognitionRequest()
var recognitionTask: SFSpeechRecognitionTask?

工作设置:在 2017 iPad、iOS 11.4 上测试。Xcode 9.4.1,斯威夫特 4.1。

谢谢!

标签: iosswiftspeech-recognitionspeech

解决方案


此问题是由于AVAudioSession未设置为Record. 尝试这个。

在视图控制器中添加

let audioSession = AVAudioSession.sharedInstance()

您的最终方法将是。

func startRecording() {
    //Change / Edit Start
    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.")
    }
    //Change / Edit Finished
    // Setup audio engine and speech recognizer
    let node = audioEngine.inputNode
    let recordingFormat = node.outputFormat(forBus: 0)
    node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
        self.request.append(buffer)
    }

    // Prepare and start recording
    audioEngine.prepare()
    do {
        try audioEngine.start()
        self.status = .recognizing
    } catch {
        return print(error)
    }

    // Analyze the speech
    recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
        if let result = result {
            self.tview.text = result.bestTranscription.formattedString
            NSLog(result.bestTranscription.formattedString)
        } else if let error = error {
            print(error)
            NSLog(error.localizedDescription)
        }
    })
}

推荐阅读