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

AVAssetWriter初始化与启动耗时过长问题求助

相机应用录制启动阻塞问题排查与解决方案需求

问题背景

我正在开发一款相机应用,使用AVAssetWriter将AVCaptureVideoDataOutput和AVCaptureAudioDataOutput的音视频缓冲区录制为mp4/mov文件。创建录制会话时,启动录制前会阻塞5-7秒,已定位两处核心耗时点。

核心耗时点分析

1. 音频AVAssetWriterInput初始化耗时过长

创建音频输入的代码如下:

// audioOutput是我的AVCaptureAudioDataOutput,audioInput是麦克风
let settings = audioOutput.recommendedAudioSettingsForAssetWriter(writingTo: .mov)
let format = audioInput.device.activeFormat.formatDescription

let audioWriter = AVAssetWriterInput(mediaType: .audio,
                                     outputSettings: settings,
                                     sourceFormatHint: format)
audioWriter.expectsMediaDataInRealTime = true

在iPhone 11 Pro上,这段代码耗时可达3000ms!但如果将outputSettings设为nil,初始化耗时仅30-50ms:

audioWriter = AVAssetWriterInput(mediaType: .audio,
                                 outputSettings: nil)
audioWriter.expectsMediaDataInRealTime = true

2. AVAssetWriter启动耗时过长

调用assetWriter.startWriting()方法在iPhone 11 Pro上耗时3000-5000ms!

我认为使用recommendedAudioSettingsForAssetWriter是正确的配置方式,但3秒的初始化时间完全无法接受。

补充信息

推荐配置详情

  • 视频推荐设置(初始化耗时约10ms):
["AVVideoCompressionPropertiesKey": {
    AllowFrameReordering = 1;
    AllowOpenGOP = 1;
    AverageBitRate = 47848572;
    BaseLayerFrameRate = 15;
    ExpectedFrameRate = 60;
    MaxAllowedFrameQP = 41;
    MaxKeyFrameIntervalDuration = 1;
    MinAllowedFrameQP = 15;
    MinimizeMemoryUsage = 1;
    Priority = 80;
    ProfileLevel = "HEVC_Main_AutoLevel";
    RealTime = 1;
    RelaxAverageBitRateTarget = 1;
},
 "AVVideoWidthKey": 2160,
 "AVVideoCodecKey": hvc1,
 "AVVideoHeightKey": 3840]
  • 音频推荐设置(初始化耗时约1500-3000ms):
["AVEncoderQualityForVBRKey": 91,
 "AVEncoderBitRatePerChannelKey": 96000,
 "AVEncoderBitRateStrategyKey": AVAudioBitRateStrategy_Variable,
 "AVFormatIDKey": 1633772320,
 "AVNumberOfChannelsKey": 1,
 "AVSampleRateKey": 44100]

关键冲突发现

音频AVAssetWriter初始化耗时久的核心原因是,初始化操作与音频AVCaptureSession启动操作并行执行:

audioQueue.async { // <-- 原本期望异步非阻塞
  AVAudioSession.sharedInstance().setCategory(.playAndRecord,
                                              options: [.mixWithOthers,
                                                        .allowBluetoothA2DP,
                                                        .defaultToSpeaker,
                                                        .allowAirPlay])
  audioCaptureSession.startRunning() // <-- 耗时1.5-3s
}
let audioWriter = AVAssetWriterInput(...) // <-- 使用推荐设置

推测AVAssetWriter内部与AVAudioSession存在互斥锁,导致两者无法真正并行执行。但我无法提前启动音频会话——避免用户打开应用且正在播放音乐时出现音频卡顿,而Snapchat能做到即时启动,求可行解决方案?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 17:42:47