Jake Jake - 1 year ago 135
Swift Question

How to get current length of AVCaptureMovieFileOutput while recording to display on screen?

As title says, I am looking to display the current length of the recording while a user is recording video with AVFoundation. I have done something similar with AVAudioRecorder where I create a timer that sets a label's text as follows:

recordDurationLabel.text = timeString((audioRecorder?.currentTime)!)

I was wondering if there is a "currentTime" feature for recording video? My only other thought would be to start a repeated 1 second timer in the captureOutput:didStartRecordingToOutputFileAtURL function but I want to ensure accuracy.

Thanks in advance!

For now this is the function I've implemented in the captureOutput:didStartRecordingToOutputFileAtURL delegate method, but again, would be cleaner to have something directly related to the video.

func startRecordingUpdateTimer() {

recordingUpdateTimer = NSTimer(timeInterval: 1.0/45.0, target: self, selector: #selector(recordedVideo), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(recordingUpdateTimer!, forMode: NSRunLoopCommonModes)

func recordedVideo() {
durationTime = durationTime + 1.0/45.0
let durationString = timeString(durationTime)
recordDurationLabel.text = durationString

Answer Source

With an AVCaptureMovieFileOutput, you can get the duration of the movie by using recordedDuration which is read only and will return you a CMTime when the recording has started. See AVCaptureFileOutput.

If you use captureOutput:didOutputSampleBuffer:fromConnection: you'll receive CMSampleBufferobjects which contain a CMTimethat you can access with CMSampleBufferGetPresentationTimeStamp.

Doing a CMTime operation like CMTimeSubstract will allow you to calculate the time difference between the current buffer and the first one you recorded.

If you have never manipulated sampleBuffers, you should take a look at this example code from Apple: RosyWriter

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