2

我设法通过该教程从麦克风中获取样本。我将方法最小化processBuffer:以将样本复制到 audioBuffer。我的问题是,如何将 AudioBuffer 转换为 NSData?

4

1 回答 1

0

以下代码应产生转换。

-(NSData *)processBuffer: (AudioBufferList*) audioBufferList

{

    AudioBuffer sourceBuffer = audioBufferList->mBuffers[0];

    // we check here if the input data byte size has changed
    if (inAudioBuffer.mDataByteSize != sourceBuffer.mDataByteSize) {
        // clear old buffer
        free(inAudioBuffer.mData);
        // assing new byte size and allocate them on mData
        inAudioBuffer.mDataByteSize = sourceBuffer.mDataByteSize;
        inAudioBuffer.mData = malloc(sourceBuffer.mDataByteSize);
    }
    int currentBuffer =0;
    int maxBuf = 800;

    NSMutableData *data=[[NSMutableData alloc] init];
    // CMBlockBufferRef blockBuffer;
    // CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(ref, NULL, &audioBufferList, sizeof(audioBufferList), NULL, NULL, 0, &blockBuffer);
    // NSLog(@"%@",blockBuffer);


    // audioBufferList->mBuffers[0].mData, audioBufferList->mBuffers[0].mDataByteSize
    for( int y=0; y<audioBufferList->mNumberBuffers; y++ )
    {
        if (currentBuffer < maxBuf){
            AudioBuffer audioBuff = audioBufferList->mBuffers[y];
            Float32 *frame = (Float32*)audioBuff.mData;


            [data appendBytes:frame length:inAudioBuffer.mDataByteSize];
            currentBuffer += audioBuff.mDataByteSize;
        }
        else{
            break;
        }

    }

  return data;

    // copy incoming audio data to the audio buffer (no need since we are not using playback)
    //memcpy(inAudioBuffer.mData, audioBufferList->mBuffers[0].mData, audioBufferList->mBuffers[0].mDataByteSize);
}
于 2014-07-23T15:30:42.637 回答