AVAssetWriter:开始写入时出现暂时滞后

时间:2019-02-22 04:40:36

标签: ios swift avfoundation avassetwriter

我正在开发一个使用AVAssetWriter录制视频的应用程序(源媒体是从captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection)输出的样本缓冲区。

我注意到,我第一次实例化我的AVAssetWriter,然后调用startWriting()startSession(atSourceTime: CMTime)时,大约有30毫秒的延迟。这会导致屏幕上的视频预览暂时停止,这也导致视频的前几帧无法正确写入。

奇怪的是,如果我随后重新实例化AVAssetWriter并再次执行所有相同的步骤,则从那时起一切正常。这只是第一次发生。

虽然可能太长而无法发布,但是我可以确定该函数正在发生错误;

func insert(pixel buffer: CVPixelBuffer, with time: CMTime) {

    // Check for unknown status
    if fileWriter.status == .unknown {
        guard startingVideoTime == nil else {
            print("We've received an error setting the starting video time.")
            return
        }
        startingVideoTime = time
        if fileWriter.startWriting() {
            fileWriter.startSession(atSourceTime: startingVideoTime!)
            isRecording = true
        }
    }

    // Append buffer
    if videoInput.isReadyForMoreMediaData {
        append(pixel: buffer, with: time)
        isRecording = true
    }
}

为后代,我从我的captureOutput调用上述函数,仅当我在用户点击“开始记录”按钮时设置的self.isRecording = true时才调用。

1 个答案:

答案 0 :(得分:0)

let videoCompressionSettings: [String: Any] = [
  AVVideoCodecKey: AVVideoCodecType.h264,
  AVVideoWidthKey: NSNumber(value: 1080),
  AVVideoHeightKey: NSNumber(value: 1920)
]
let audioCompressionSettings: [String: Any] = [
  AVNumberOfChannelsKey: NSNumber(value: 1),
  AVEncoderAudioQualityForVBRKey: NSNumber(value: 91),
  AVEncoderBitRatePerChannelKey:NSNumber(value: 9600),
  AVEncoderBitRateStrategyKey: AVAudioBitRateStrategy_Variable,
  AVFormatIDKey: NSNumber(value: 1633772320),
  AVSampleRateKey: NSNumber(value: 44100)
]
// My own wrapper for AVAssetWriter
movieWriterManager = MovieWriterManager(videoUrl: recordingVideoURL(), audioUrl: recordingAudioURL(), videoCompressionSettings: videoCompressionSettings, audioCompressionSettings: audioCompressionSettings)
movieWriterManager?.warmup()

您可以尝试通过在AppDelegate的didFinishLaunchingWithOptions上使用默认的videoCompressionSettings和audioCompressionSettings运行相同的步骤来争取时间。实际上,它并不是在阻止UI线程,而只是在阻止AVCaptureVideoDataOutput的视频输出连接。