AVAudioRecorder 仅适用于 .record(forDuration:)

问题描述

在我的一生中,我一直无法让 AVAudioRecorder 使用 record() 方法正确录制声音。如果我使用 record(forDuration:) 方法,我只能录制声音。我尝试过多种设备(带 iOS 14 的 iPhone 8、带 iOS 14 的 iPad Air(第 7 代)、iPhone 12 迷你模拟器)。我还将构建目标从 iOS 13 更改为 iOS 9,并在较旧的模拟器(带 iOS 10 的 iPhone 8)上进行了尝试。

无论如何,对于我的设备/iOS 组合,行为总是相同的 - 停止录制时 record() 总是产生一个空的 4kb 音频文件。我已经探索了模拟器容器,并下载了设备容器来验证这一点。同样,record(forDuration:) 将使用实际录制的声音保存正确的音频文件。

Xcode 版本:12.3

罪魁祸首:

func recordAudio() {
        let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as String
        let recordingName = "recordedVoice.m4a"
        let pathArray = [dirPath,recordingName]
        let filePath = URL(string: pathArray.joined(separator: "/"))
        
        let session = AVAudioSession.sharedInstance()
        try! session.setCategory(.playAndRecord,mode: .default,options: .defaultToSpeaker)
        try! session.setActive(true)
        
        try! self.audioRecorder = AVAudioRecorder(url: filePath!,settings: [:])
        self.audioRecorder.delegate = self
        self.audioRecorder.isMeteringEnabled = true
        self.audioRecorder.prepareToRecord()

        // Problematic section
        // I only use one of the following two lines,record() fails,record(forDuration:) works.
        self.audioRecorder.record()
        self.audioRecorder.record(forDuration: 5)
}

func stopRecord() {
        self.audioRecorder.stop()
        let audioSession = AVAudioSession.sharedInstance()
        try! audioSession.setActive(false)
}

record() 的静默失败 - 没有错误或崩溃。

我刚刚发现的另一件有趣的事情。当我调用 audioRecorder.stop() 时,应用程序无法正确保存音频文件。无论我使用 record() 还是 record(forDuration:)

我很困惑。任何帮助表示赞赏。

解决方法

record() 的静默失败 - 没有错误或崩溃。

在实例化 'fmt?' 时出现 AVAudioRecorder 错误。提供设置字典修复它。

let settings = [
    AVFormatIDKey: kAudioFormatMPEG4AAC,AVSampleRateKey: 44100,AVNumberOfChannelsKey: 1
]

try! self.audioRecorder = AVAudioRecorder(url: filePath!,settings: settings)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...