如何根据值 1 或 2 动态分配一维数组或二维数组?
该数组需要保存frameCount
许多浮点数,但需要拆分为 1 或 2 个通道。第一个维度是通道数,第二个维度是帧数。如果有 2 个通道,frameCount
则在 2 个维度之间进行拆分,例如 [channelNumber] [frameNumber]
我有以下代码,但我认为它不起作用。
float ** arrayToFill = (float **)malloc((frameCount*channelCount)*sizeof(float));
我的数组在调试器中看起来像这样
我需要将 float ** 传递给函数,以便它可以按如下方式填充数组
- (OSStatus) readFloatsConsecutive:(SInt64)numFrames intoArray:(float**)audio withOffset:(long)offset
{
OSStatus err = noErr;
if (!mExtAFRef) return -1;
int kSegmentSize = (int)(numFrames * mExtAFNumChannels * mExtAFRateRatio + .5);
if (mExtAFRateRatio < 1.) kSegmentSize = (int)(numFrames * mExtAFNumChannels / mExtAFRateRatio + .5);
AudioBufferList bufList;
UInt32 numPackets = numFrames; // Frames to read
UInt32 samples = numPackets * mExtAFNumChannels;
UInt32 loadedPackets = numPackets;
short *data = (short*)malloc(kSegmentSize*sizeof(short));
if (!data) {
NSLog(@"data is nil");
goto error;
}
bufList.mNumberBuffers = 1;
bufList.mBuffers[0].mNumberChannels = mExtAFNumChannels;
bufList.mBuffers[0].mData = data; // data is a pointer (short*) to our sample buffer
bufList.mBuffers[0].mDataByteSize = samples * sizeof(short);
@synchronized(self) {
err = ExtAudioFileRead(mExtAFRef, &loadedPackets, &bufList);
}
if (err) goto error;
if (audio) {
for (long c = 0; c < mExtAFNumChannels; c++) {
if (!audio[c]) continue;
for (long v = 0; v < numFrames; v++) {
if (v < loadedPackets) audio[c][v+offset] = (float)data[v*mExtAFNumChannels+c] / 32768.f;
else audio[c][v+offset] = 0.f;
}
}
}
error:
free(data);
if (err != noErr) return err;
if (loadedPackets < numFrames) mExtAFReachedEOF = YES;
mRpos += loadedPackets;
return loadedPackets;
}