Search code examples
iosavassetwriteravassetwriterinput

Get duration of video while it's being recorded with AVAssetWriter


I have a class to record video and audio into .mp4 file. I use AVAssetWriter, AVAssetWriterInput to do such task

How can I get duration of a video while it's being recorded with such method (AVAssetWriter)?


Solution

  • You can save start time when you begin startSession

    let startTimeStamp = CMSampleBufferGetPresentationTimeStamp(sample)
    fileWriter.startSession(atSourceTime: startTimeStamp)
    startTime = Double(startTimeStamp.value) / Double(startTimeStamp.timescale)
    

    than every buffer you will get do this:

    let currentTimeStamp = CMSampleBufferGetPresentationTimeStamp(sample)
    let currentTime = Double(currentTimeStamp.value) / Double(currentTimeStamp.timescale)
    
    print("Duration - \(currentTime - startTime)")