问题出现的原因可能是写入速度过慢,导致下一个可用的缓冲区未能及时提供给AVAssetWriterInput。可以通过以下代码解决:
//初始化AVAssetWriterInput对象和output设置
let videoOutputSettings: Dictionary = [
AVVideoCodecKey: AVVideoCodecType.h264,
AVVideoWidthKey: frameSize.width,
AVVideoHeightKey: frameSize.height
]
videoWriterInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoOutputSettings)
let videoInputQueue = DispatchQueue(label: "video input queue")
videoWriterInput!.expectsMediaDataInRealTime = true
//将AVAssetWriterInput与AVAssetWriter绑定
let videoOutput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoWriterInput!, sourcePixelBufferAttributes: nil)
videoWriter?.add(videoWriterInput!)
//在capture输出数据中调用下面的方法来写入视频数据到AVAssetWriterInput中
func writeVideo(buffer: CVPixelBuffer, time: CMTime) -> Void {
if (videoWriterInput!.isReadyForMoreMediaData) {
videoInputQueue.sync {
if let adpator = videoOutput {
adpator.append(buffer, withPresentationTime: time)
}
}
}
}
在以上代码中,我们使用videoInputQueue来确保append()请求按照顺序调用,并且我们检查了AVAssetWriterInput的可用性,以确保不会在未准备好时提供更多的数据。