I am working on an audio recorder and using AQRecorder from SpeakHere Sample code. I want to add a slider on UI to display recording duration. I did this using simple timer initialized at start of recording. But sometimes recording is lagged behind by 1 second. eg, Slider is displaying 10 sec but the actual duration of audio on saving is 9 second.
Is there any way so that I can get exact duration while recording for updating slider, instead of using timer.
I tried following methods also
NSTimeInterval AQRecorder::GetTotalDuration()
{
UInt64 nPackets;
UInt32 propsize = sizeof(nPackets);
XThrowIfError (AudioFileGetProperty(mRecordFile, kAudioFilePropertyAudioDataPacketCount, &propsize, &nPackets), "kAudioFilePropertyAudioDataPacketCount");
Float64 fileDuration = (nPackets * mRecordFormat.mFramesPerPacket) / mRecordFormat.mSampleRate;
return fileDuration;
}
NSTimeInterval AQRecorder::GetCurrentTime() {
double timeInterval = 0;
AudioQueueTimelineRef timeLine;
OSStatus status = AudioQueueCreateTimeline(mQueue, &timeLine);
if(status == noErr) {
AudioTimeStamp timeStamp;
AudioQueueGetCurrentTime(mQueue, timeLine, &timeStamp, NULL);
timeInterval = timeStamp.mSampleTime * 1.0 / mRecordFormat.mSampleRate; // modified
}
return timeInterval;
}
But the first one gives length of packets written into file, which is always less then the actual recording duration. Second one is also not giving exact duration (increased by 1-2 second).
Please help if someone has implemented the same. Thanks.
SpeakHere has a function that will provide some great clues about how to calculate the actual duration of the recording. It's
CalculateBytesForTime
. You want to do the opposite of course, but the same principles apply.When you know your audio format, you can work backwards to work out the duration.
Check out Apple's docs Set Up an Audio Format for Recording for a detailed explanation. Also have a look at the Write a Function to Derive Playback Audio Queue Buffer Size. The latter tells you how to calculate the buffer size based on the number in the parameter
seconds
. Again, depending on your audio format, you can work the other way to determineseconds
based on your buffer size.