使用 AVAssetWriter 捕获的视频的持续时间为零

Captured video with AVAssetWriter have duration zero

我正在尝试使用 AVAssetWriterAVCaptureSessionAVCaptureOutputAVAssetWriterInput 捕捉视频。

这是 AVCaptureOutput 的委托方法,我在其中添加缓冲区:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {


    if (self.assetWriter.status != AVAssetWriterStatusWriting) {

        CMTime startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);

        [self.assetWriter startWriting];

        [self.assetWriter startSessionAtSourceTime:startTime];
    }
    if ([captureOutput isKindOfClass:AVCaptureVideoDataOutput.class] && self.videoWriterInput.isReadyForMoreMediaData) {

        [self.videoWriterInput appendSampleBuffer:sampleBuffer];
    }
    else if ([captureOutput isKindOfClass:AVCaptureAudioDataOutput.class] && self.audioWriterInput.isReadyForMoreMediaData) {

        [self.audioWriterInput appendSampleBuffer:sampleBuffer];
    }
}

以及完成写作的方法:

- (void)finishCurrentWriting {

    [self.videoWriterInput markAsFinished];
    [self.audioWriterInput markAsFinished];

    __weak ViewController *weakSelf = self;

    [self.assetWriter finishWritingWithCompletionHandler:^{

        dispatch_async(dispatch_get_main_queue(), ^{

            [weakSelf runVideo];
        });
    }]; 
}

当我结束将视频写入文件时,我正在尝试通过 MPMoviePlayerController 播放它。数据可用是因为文件很大,但由于某些原因,视频的持续时间为零。我做错了什么?

添加了 repository 测试代码。它用于 HLS 流,所以现在它应该制作 15 秒的视频,然后在屏幕底部的播放器中显示(现在播放器只是黑色,视频时长为 0)。

确保在完成后调用 [AVAssetWriter finishWritingWithCompletionHandler:]

您应该使用收到的第一个缓冲区的显示时间戳调用 startSessionAtSourceTime

您可以删除 [self.assetWriter endSessionAtSourceTime:kCMTimeZero];

[self.assetWriter endSessionAtSourceTime:kCMTimeZero];

您正在将会话结束时间设置为零,使录制长度为 0 秒...