AudioBuffer到NSData

时间:2013-08-06 13:43:07

标签: ios audiotoolbox

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

1 个答案:

答案 0 :(得分: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);
}