Mike Schmidt Mike Schmidt - 4 years ago 336
Swift Question

AVAssetWriter Recording Video in Swift?

I have successfully set up AVAssetWriter to record and save video to my camera roll. The only problem is that the first frame of the recorded video is a blank white frame. Is there a way I can get around this? What is going on?

Answer Source

Are you doing any manipulation on video frames? In my case I was resizing the video frames before writing them. In this case, audio frames were written first and after few frames, video frames were written. Due to this, the first few frames were shown white in the preview. But it was hardly noticeable in the video playback.

Solution :

Skip writing audio frames till you write a video frame using avasssetwriter


Recommended code for captureoutput

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection!) {

    if CMSampleBufferDataIsReady(sampleBuffer) == false
    {
      // Handle error
      return;
    }
    startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)

    if videoWriter.status == AVAssetWriterStatus.Unknown {
                videoWriter.startWriting()
                videoWriter.startSessionAtSourceTime(startTime)
                return 
        }

    if videoWriter.status == AVAssetWriterStatus.Failed {
      // Handle error here
      return;
    }

    // Here you collect each frame and process it

    if(recordingInProgress){

    if let _ = captureOutput as? AVCaptureVideoDataOutput {

        if videoWriterInput.isReadyForMoreMediaData{
            videoWriterInput.append(sampleBuffer)
            video_frames_written = true
        }
    }
    if let _ = captureOutput as? AVCaptureAudioDataOutput {
            if audioWriterInput.isReadyForMoreMediaData && video_frames_written{
                audioWriterInput.append(sampleBuffer)
            }

        }

    }

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download