objective-cmacoscore-audioaudioqueueservices

How to get raw audio data from AudioQueueRef in MacOS?


I am trying to get the raw audio data from the system microphone using AudioToolbox and CoreFoundation frameworks. So far the writing packets to file logic works but when I try to capture the raw data into a file, some values are 0.

static void MyAQInputCallback(void *inUserData, AudioQueueRef inQueue,
                             AudioQueueBufferRef inBuffer,
                             const AudioTimeStamp *inStartTime,
                             UInt32 inNumPackets,
                             const AudioStreamPacketDescription *inPacketDesc)
{
   MyRecorder *recorder = (MyRecorder *)inUserData;
   
   if (inNumPackets > 0)
   {
       
       CheckError(AudioFileWritePackets(recorder->recordFile, FALSE, inBuffer->mAudioDataByteSize,
                                        inPacketDesc, recorder->recordPacket, &inNumPackets, 
                                        inBuffer->mAudioData), "AudioFileWritePackets failed");
       
       recorder->recordPacket += inNumPackets;
       int sampleCount = inBuffer->mAudioDataBytesCapacity / sizeof(AUDIO_DATA_TYPE_FORMAT);
       
       AUDIO_DATA_TYPE_FORMAT* samples = (AUDIO_DATA_TYPE_FORMAT*)inBuffer->mAudioData;
       FILE *fp = fopen(filename, "a");
       for (int i = 0; i < sampleCount; i++){
           fprintf(fp, "%i;\n",samples[i]);
       }
       fclose(fp);
       
   }
   
   if (recorder->running)
       CheckError(AudioQueueEnqueueBuffer(inQueue, inBuffer,
                                          0, NULL), "AudioQueueEnqueueBuffer failed");
}

And some properties:

NumberRecordBuffers = 3
buffer duration = 0.1
format->mFramesPerPacket = 1024
samplerate = 44100
inNumPackets = 4

Out of 1024 samples, only about 400 is filled. Increasing the buffer duration increases the valid numbers proportionally but the overall data still contains gaps. The audio file that is written has no such error. Any help is appreciated. Thank you in advance.


Solution

  • Solved it using recordFormat.mFormatID = kAudioFormatLinearPCM for recording and using

    int sampleCount = inBuffer->mAudioDataByteSize / sizeof(AUDIO_DATA_TYPE_FORMAT)