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

时间:2016-12-08 11:04:38

标签: ios objective-c video avfoundation avassetwriter

我尝试使用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流媒体,所以现在它应该制作15s视频,之后显示在屏幕底部的播放器中(现在播放器只是黑色,视频持续时间为0)。

2 个答案:

答案 0 :(得分:1)

确保在您完成后致电[AVAssetWriter finishWritingWithCompletionHandler:]

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

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

答案 1 :(得分:0)

[self.assetWriter endSessionAtSourceTime:kCMTimeZero];

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