How to update time label during recording using this capture pipeline in AVFoundation:
Mic -> AVCaptureDeviceInput -> AVCaptureSession -> AVCaptureAudioDataOutput
var currentTime: TimeInterval
// The time, in seconds, since the beginning of the recording.
let masterClock = CMClockGetHostTimeClock() // This masterclock should be from captureSession
var timebase: CMTimebase? = nil
CMTimebaseCreateWithMasterClock(kCFAllocatorDefault, masterClock, &timebase)
CMTimebaseSetRate(timebase!, 1.0) // Start/Resume recording
CMTimebaseSetRate(timebase!, 0.0) // Pause Recording
When you're dealing with AVCaptureAudioOutput, you're now working with Sample Buffers. Regardless of if it's Video or Audio, you need two critical pieces of information, the sample data, and the time that sample data was recorded.
This is the "Clock" https://developer.apple.com/reference/coremedia/cmclock
A clock represents a source of time information: generally, a piece of hardware that measures the passage of time.
It's highly accurate, and that's really the point. It's read only, you can only grab a reference from it and you can't set it. All sorts of things can happen to buffers, they get queued, they can be forwarded over a network, but if you have that CMTime reference, they can be reconstructed into the right order and the right time.
CMSync is a subset of functions that deals with Clock drift (between two different clocks reporting slightly different values). You don't need to worry about these at all.
Actually to do what you want is very simple. Here's an example you can cut and paste into a playground.
import AVFoundation let masterClock : CMClock = CMClockGetHostTimeClock() let startTime : CMTime = CMClockGetTime(masterClock) sleep(1) let endTime : CMTime = CMClockGetTime(masterClock) let difference : CMTime = CMTimeSubtract(endTime, startTime) let seconds = CMTimeGetSeconds(difference)
That should give you a seconds value of slightly > 1.
When you click the record button in your application, grab the AVCaptureSession clock and capture the startTime.
When you want to update the UI, just check the AVCaptureSession clock again, subtract the two CMTime's and convert to seconds.
Just make sure that you don't update the UI on every sample buffer, that would be far too frequent, so maybe do it only every 14,000 samples or so (or whatever works for the audio frequency you're using). Also make sure to offload that to a separate thread.
Hope this helps and explains a little bit on the Clocks. Good luck!