1

I'm trying to capture video with AVAssetWriter, AVCaptureSession, AVCaptureOutput and AVAssetWriterInput.

Here is delegate method for AVCaptureOutput where I'm adding buffers:

- (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];
    }
}

And method for finishing writing:

- (void)finishCurrentWriting {

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

    __weak ViewController *weakSelf = self;

    [self.assetWriter finishWritingWithCompletionHandler:^{

        dispatch_async(dispatch_get_main_queue(), ^{

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

When I'm ending writing video into file, I'm trying to play it via MPMoviePlayerController. The data is available because file have significant size, but for some reasons, the duration of video is zero. What am I doing wrong?

Added repository with test code. It is for HLS streaming, so for now it should make 15s videos and after that display it in player on bottom of screen(now player is just black, and video duration is 0).

Vasyl Khmil
  • 2,548
  • 1
  • 20
  • 36

2 Answers2

1

Make sure to call [AVAssetWriter finishWritingWithCompletionHandler:] when you've finished.

You should be calling startSessionAtSourceTime with presentation time stamp of the first buffer you receive.

You can delete the [self.assetWriter endSessionAtSourceTime:kCMTimeZero]; .

Rhythmic Fistman
  • 34,352
  • 5
  • 87
  • 159
0
[self.assetWriter endSessionAtSourceTime:kCMTimeZero];

You are setting the session end time to zero, making the recording 0 seconds long...

Lefteris
  • 14,550
  • 2
  • 56
  • 95
  • And what should I set there? Lets say, I have NSTimeInterval value with video duration. – Vasyl Khmil Dec 08 '16 at 11:24
  • This depends on your fps and duration. [Look here for some explanation](http://stackoverflow.com/a/13001917/312312) and also [here](http://stackoverflow.com/questions/4001755/trying-to-understand-cmtime-and-cmtimemake) – Lefteris Dec 08 '16 at 11:29