ios - 语音识别和音频播放在模拟器上工作但不在 iPhone 上?
问题描述
我试图使用语音识别将其转换为文本并显示它。语音识别和音频播放在模拟器上工作但不在 iPhone 上?为什么会这样 ?
在 iphone 上尝试识别时,我在控制台中收到此错误:
域=kAFAssistantErrorDomain 代码=203“损坏”用户信息={NSLocalizedDescription=损坏,NSUnderlyingError=0x28063f240 {错误域=SiriSpeechErrorDomain 代码=102“(空)”}}
那是我的代码:
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
self.animateSpinner(forStatus: false)
do {
try audioPlayer = AVAudioPlayer(contentsOf: recorder.url)
audioPlayer.play()
} catch let error {
debugPrint(error)
}
SFSpeechRecognizer.requestAuthorization({ (authStatus) in
if authStatus == .authorized {
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: self.language))
let request = SFSpeechURLRecognitionRequest(url: recorder.url)
recognizer?.recognitionTask(with: request, resultHandler: { (result, err) in
if let err = err {
debugPrint(err)
return
}
self.textView.text = result?.bestTranscription.formattedString
})
}
})
}
这是 viewDidLoad() 中记录器的设置
func setupRecorder() {
let dirPaths = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)
let soundFileURL = dirPaths[0].appendingPathComponent("sound.caf")
do {
audioRecorder = try AVAudioRecorder(url: soundFileURL, settings: [
AVEncoderAudioQualityKey: AVAudioQuality.min.rawValue,
AVEncoderBitRateKey: 16,
AVNumberOfChannelsKey: 2,
AVSampleRateKey: 44100.0])
audioRecorder.delegate = self
audioRecorder.prepareToRecord()
}
catch let error {
debugPrint(error)
}
}
解决方案
调用它viewDidLoad
解决了这个问题:
var audioSession: AVAudioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSession.Category.playAndRecord, mode: .spokenAudio, options: .defaultToSpeaker)
try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
} catch let error{
print("audioSession properties weren't set because of an error: ", error)
}
推荐阅读
- javascript - 从 querySelectorAll() 获取 element.values
- pushdown-automaton - 描述该语言的下推自动机
- python - 如何打开文件、替换一些字符串并将更新保存到同一个文件?
- git - 无法使用 PAT 从 Azure DevOps 克隆 git
- javascript - 如果单击了元素,则检测表单元素是否已更改,如果已更改 #anchor
- vba - 在 VBA 中查找中位数
- angular - 用于隐藏打印元素的 Angular 指令
- java - JPA:冗余保存反模式
- r - 书本图标题宽度?
- ssis - 使用 SSIS 为流程创建 ETL JOB