首页 > 解决方案 > 为什么 AVAudioRecorder 在使用 kAudioFormatMPEGLayer3 格式时会抛出错误?

问题描述

我正在尝试以 mp3 格式录制音频,但是当我使用时kAudioFormatMPEGLayer3 AVAudioRecorder会引发错误。

代码是

获取文件路径

func getFileUrl() -> URL
{
    let filename = "myRecording.mp3"
    let filePath = getDocumentsDirectory().appendingPathComponent(filename)
    return filePath
}

创造AVAudioRecorder

  func setup_recorder()
{
       if isAudioRecordingGranted
       {
        let session = AVAudioSession.sharedInstance()
        do
        {
            try  session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
            try session.setActive(true)
            let settings = [
                AVFormatIDKey: Int(kAudioFormatMPEGLayer3),
                AVSampleRateKey: 44100,
                AVNumberOfChannelsKey: 2,
                AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue
            ]
            audioRecorder = try AVAudioRecorder(url: getFileUrl(), settings: settings)
            audioRecorder.delegate = self
            audioRecorder.isMeteringEnabled = true
            audioRecorder.prepareToRecord()
        }
        catch let error {
            display_alert(msg_title: "Error", msg_desc: error.localizedDescription, action_title: "OK")
        }
    }
    else
    {
        display_alert(msg_title: "Error", msg_desc: "Don't have access to use your microphone.", action_title: "OK")
    }
}

提前致谢。

标签: iosswiftavaudiorecorder

解决方案


推荐阅读