im试图使用语音识别将其转换为文本并显示。语音识别和音频播放可以在模拟器上运行,但不能在iPhone上运行吗?为什么会这样 ?
我尝试在iPhone上识别时在控制台中收到此错误:
Domain = kAFAssistantErrorDomain代码= 203“ Corrupt” UserInfo = {NSLocalizedDescription = Corrupt,NSUnderlyingError = 0x28063f240 {Error Domain = SiriSpeechErrorDomain Code = 102“(null)”}}
那是我的代码:
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)
}
}
答案 0 :(得分:0)
在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)
}
答案 1 :(得分:0)
SFSpeechRecognizer.requestAuthorization { authStatus in
if authStatus == SFSpeechRecognizerAuthorizationStatus.authorized {
if let path = Bundle.main().urlForResource("test", withExtension: "m4a") {
let recognizer = SFSpeechRecognizer()
let request = SFSpeechURLRecognitionRequest(url: path)
request.cancel()
recognizer?.recognitionTask(with: request, resultHandler: { (result, error) in
if let error = error {
print("There was an error: \(error)")
} else {
print (result?.bestTranscription.formattedString)
}
})
}
}
}
在开始识别之前取消请求。在这里检查代码
答案 2 :(得分:0)
对我来说,添加
inputNode.removeTap(onBus: 0)
sleep(1)
之前
inputNode.installTap(onBus: 0, bufferSize: 4096, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
self.recognitionRequest?.append(buffer)}
解决问题