要解决AVPlayerItemVideoOutput的copyPixelBuffer方法始终返回1280x720的问题,您可以使用以下代码示例来指定所需的输出大小:
import AVFoundation
// 创建一个 AVPlayerItemVideoOutput 实例
let videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA])
// 指定输出的大小为 1920x1080
let outputSize = CGSize(width: 1920, height: 1080)
// 获取 AVPlayerItem 的当前视频轨道
let videoTrack = playerItem.tracks(withMediaType: .video).first
// 计算视频的自然大小
let naturalSize = videoTrack?.naturalSize
// 计算视频的缩放比例
let scale = max(outputSize.width / naturalSize.width, outputSize.height / naturalSize.height)
// 计算要渲染的视频大小
let scaledSize = CGSize(width: naturalSize.width * scale, height: naturalSize.height * scale)
// 创建一个 AVPlayerItemVideoOutput 实例并指定输出大小
let videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
kCVPixelBufferWidthKey as String: scaledSize.width,
kCVPixelBufferHeightKey as String: scaledSize.height])
// 将 AVPlayerItemVideoOutput 添加到 AVPlayerItem 中
playerItem.add(videoOutput)
// 在需要时使用 copyPixelBuffer 方法来获取指定大小的视频帧
let pixelBuffer = videoOutput.copyPixelBuffer(forItemTime: playerItem.currentTime(), itemTimeForDisplay: nil)
请注意,上述代码中的 playerItem
是您的 AVPlayerItem 实例,您需要将其替换为您实际使用的实例。此外,您可能还需要根据需要在代码中添加其他逻辑和错误处理。