ios - 语音识别器不返回答案
问题描述
我正在关注有关 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。
谢谢!
解决方案
此问题是由于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)
}
})
}
推荐阅读
- java - 将 Datastore 实体导入 Eclipse 模拟器
- javascript - 为什么变量在 Javascript 中保持不变?
- pandas - pandas_profiling 运行时间过长
- kubernetes - 如何在没有云提供商或 LB 的情况下获取 pod 内的客户端 ip
- javascript - 按下按钮后使用javascript打开表单
- firefox - 如何在firefox上使用javascript转换功能画中画
- java - 即使在 HotSpot 中没有带有 CMS 的 Full GC 的情况下,Old Generation 的大小如何减小?
- solr - 如何在 Hybris 的 Solr 更新中跳过坏文档
- grafana - InfluxDB 时间落后 15 分钟
- sql - 如何在Oracle中按日期分组和排序?