Black frames in recorded videos

While using the native AVfoundation for recording videos I am able to see black frames/ screen in the beginning and end of the video for 2 millisecond at the end and beginning .

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {

guard isRecording, let assetWriter = assetWriter else { return }

let timestamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
    
    if recordingStartTime == nil {
        recordingStartTime = timestamp
        let adjustedStartTime = CMTimeAdd(timestamp, CMTimeMake(value: -2, timescale: 1000)) // Adjust start time slightly earlier
        assetWriter.startSession(atSourceTime: adjustedStartTime)
        print("Status: \(assetWriter.status.rawValue)")
    }
    
    if output == videoOutput {
        if videoInput?.isReadyForMoreMediaData == true {
            videoInput?.append(sampleBuffer)
        }
    } else if output == audioOutput {
        if audioInput?.isReadyForMoreMediaData == true {
            audioInput?.append(sampleBuffer)
        }
    }
    
    if let startTime = recordingStartTime, CMTimeSubtract(timestamp, startTime) >= recordingInterval {
        isRecording = false
        let adjustedEndTime = CMTimeAdd(timestamp, CMTimeMake(value: 2, timescale: 1000)) // Adjust end time slightly later
        assetWriter.finishWriting { [weak self] in
            print("Finished writing segment")
            self?.startRecording() // Start a new recording segment
        }
        recordingStartTime = nil
    }
}

I had a similar problem in recording video from the camera. I had to add the AVCaptureMovieFileOutput to the capture session right after setting up the AVCaptureDevice. When the user pressed the record button at a later time it worked without black frames. But when I did set up the AVCaptureMovieFileOutput only after the user pressed record I got black frames at the start of the recorded movie.

Does anyone know what is the problem here?

Black frames in recorded videos
 
 
Q