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

macOS中AVCaptureVideoDataOutput设置AVVideoProfileLevelKey报错求助

解决AVCaptureVideoDataOutput设置AVVideoProfileLevelKey报错的问题

这个问题我之前也踩过坑,根源是你混淆了不同AVCapture输出组件的配置规则——AVCaptureVideoDataOutput的videoSettings字典根本不支持AVVideoProfileLevelKey!

为什么会报错?

AVCaptureVideoDataOutput的核心作用是输出未编码的原始视频帧(CVPixelBuffer),它的videoSettings只负责指定帧的像素格式,比如BGRA32、YUV420等。而AVVideoProfileLevelKey是用于编码场景的配置键(比如用AVAssetWriter写入H.264视频、或者AVCaptureMovieFileOutput录制文件时),放到VideoDataOutput的设置里自然会被判定为无效键。

正确的配置方式

根据你的需求,分两种情况处理:

1. 仅需要获取特定格式的视频帧

如果只是想控制VideoDataOutput输出的像素格式,直接用kCVPixelBufferPixelFormatTypeKey即可:

let captureSession = AVCaptureSession()
var videoCaptureOutput = AVCaptureVideoDataOutput()

// 设置输出BGRA32格式的帧(常用的图像处理格式)
videoCaptureOutput.videoSettings = [
    kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA
]

// 别忘了把output添加到session里
captureSession.addOutput(videoCaptureOutput)

2. 需要控制视频编码的Profile Level

如果你的目标是编码视频(比如写入文件),那编码参数应该放到AVAssetWriterInput的配置里,而不是VideoDataOutput:

// 假设已经创建了AVAssetWriter实例
let videoOutputSettings: [String: Any] = [
    AVVideoCodecKey: AVVideoCodecType.h264,
    AVVideoWidthKey: 1920,
    AVVideoHeightKey: 1080,
    // 编码压缩参数里才放Profile Level
    AVVideoCompressionPropertiesKey: [
        AVVideoProfileLevelKey: AVVideoProfileLevelH264HighAutoLevel,
        AVVideoAverageBitRateKey: 5_000_000 // 5Mbps码率
    ]
]

let videoWriterInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoOutputSettings)
// 后续将VideoDataOutput的帧写入这个input即可

简单来说:VideoDataOutput管“获取原始帧”,编码参数交给负责“写入/编码”的组件来配置就好啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:46:59