首页 > 解决方案 > 语音识别和音频播放在模拟器上工作但不在 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)
    }
}

标签: iosswiftavfoundationavaudioplayer

解决方案


调用它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)
    }

推荐阅读