大家好,所以我找到了自己问题的答案,我只需要添加大约 10 行代码就可以让它工作。基本上我所做的是在用户数据结构中,或者苹果称之为客户端数据结构,我添加了一个变量来跟踪记录的样本总数,即采样率(这样我就可以访问内部的值回调)和一个指向音频数据的指针。在回调函数中,我为指针重新分配内存,然后将缓冲区的内容复制到新分配的内存中。
我将发布我的客户端记录器结构的代码和回调函数中的代码行。我想发布整个程序的代码,但其中大部分是从 Chis Adamson 和 Kevin Avila 的《Learning Core Audio》一书中借来的,我不想侵犯这本书所拥有的任何版权(有人可以告诉我在这里发布它是否合法?如果是,我会非常乐意发布整个程序。
客户端记录器结构代码:
//user info struct for recording audio queue callbacks
typedef struct MyRecorder{
AudioFileID recordFile;
SInt64 recordPacket;
Boolean running;
UInt32 totalRecordedSamples;
Float32 * allData;
Float64 sampleRate;
}MyRecorder;
这个结构体需要在程序的主循环中初始化。它看起来像这样:
MyRecorder recoder = {0};
我知道我拼错了“recorder”。
接下来,我在回调函数内部做了什么:
//now let's also write the data to a buffer that can be accessed in the rest of the program
//first calculate the number of samples in the buffer
Float32 nSamples = RECORD_SECONDS * recorder->sampleRate;
nSamples = (UInt32) nSamples;
//so first we need to reallocate memory that the recorder.allData pointer is pointing to
//pretty simple, just add the amount of samples we just recorded to the number that we already had
//to get the current total number of samples, and the size of each sample, which we get from
//sizeof(Float32).
recorder->allData = realloc(recorder->allData, sizeof(Float32) * (nSamples + recorder->totalRecordedSamples));
//now we need to copy what's in the current buffer into the memory that we just allocated
//however, rememeber that we don't want to overwrite what we already just recorded
//so using pointer arith, we need to offset the recorder->allData pointer in memcpy by
//the current value of totalRecordedSamples
memcpy((recorder->allData) + (recorder->totalRecordedSamples), inBuffer->mAudioData, sizeof(Float32) * nSamples);
//update the number of total recorded samples
recorder->totalRecordedSamples += nSamples;
当然,在我的程序结束时,我释放了 recoder.allData 指针中的内存。
另外,我在 C 方面的经验非常有限,所以如果我犯了一些错误,尤其是在内存管理方面,请告诉我。 C 中的一些 malloc、realloc、memcpy 等类型的函数让我大吃一惊。
编辑:我现在正在研究如何使用 AudioUnits 做同样的事情,完成后我会发布解决方案。