You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xcode14.3升级Swift旧应用:录音播放崩溃(AVAudio错误2003332927)

问题分析与解决

崩溃的核心原因是Apple Lossless(kAudioFormatAppleLossless)格式不支持手动设置比特率。该格式属于无损压缩,比特率由音频采样率、通道数等原生参数自动计算,强行指定AVEncoderBitRateKey会触发CoreAudio的参数设置错误,也就是报错里的Code=2003332927。

具体修复步骤

  • 移除AVEncoderBitRateKey和AVEncoderAudioQualityKey参数,无损格式不需要这类自定义编码参数
  • 把危险的try!替换为try并配合do-catch捕获错误,避免参数错误直接导致崩溃
  • 处理self.audioFile?.length的可选值,不要直接强制解包,防止audioFile为空时触发新崩溃

修改后的代码

func saveVoiceCganger() {
    do {
        // 保留无损格式必要参数,移除无效的比特率、质量设置
        let settings: [String: Any] = [
            AVFormatIDKey: NSNumber(value: kAudioFormatAppleLossless),
            AVNumberOfChannelsKey: 2,
            AVSampleRateKey: 44100.0
        ]
        // 用try替代try!,配合外层do-catch捕获创建文件的错误
        let newAudio = try AVAudioFile(forWriting: getOutPutUrl(), settings: settings)
        
        guard let originalLength = self.audioFile?.length else {
            print("音频文件为空,无法执行保存操作")
            return
        }
        
        self.audioEngine.mainMixerNode.installTap(onBus: 0, bufferSize: 1024, format: self.audioEngine.mainMixerNode.outputFormat(forBus: 0)) { buffer, time in
            print(newAudio.length)
            print("=====================")
            print(originalLength)
            print("**************************")
            
            if newAudio.length < originalLength {
                do {
                    try newAudio.write(from: buffer)
                } catch {
                    print("写入缓冲区失败: \(error.localizedDescription)")
                }
            } else {
                self.audioEngine.mainMixerNode.removeTap(onBus: 0)
            }
        }
    } catch {
        print("创建音频文件失败: \(error.localizedDescription)")
    }
}

额外说明

如果确实需要自定义比特率和编码质量,可以改用有损压缩格式(比如AAC),此时保留原参数即可,示例设置如下:

// AAC格式支持自定义编码参数
let settings: [String: Any] = [
    AVFormatIDKey: NSNumber(value: kAudioFormatMPEG4AAC),
    AVEncoderAudioQualityKey: AVAudioQuality.low.rawValue,
    AVEncoderBitRateKey: 320000,
    AVNumberOfChannelsKey: 2,
    AVSampleRateKey: 44100.0
]

内容的提问来源于stack exchange,提问作者DannyRoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 18:22:50