How to convert CMSampleBufferRef to NSData

RyanM picture RyanM · Dec 18, 2011 · Viewed 11.1k times · Source

How do you convert CMSampleBufferRef to NSData?

I've managed to get the data for an MPMediaItem by following Erik Aigner's answer on this thread, however the data is of type CMSampleBufferRef.

I know CMSampleBufferRef is a struct and is defined in the CMSampleBuffer Reference in the iOS Dev Library, but I don't think I fully understand what it is. None of the CMSampleBuffer functions seem to be an obvious solution.

Answer

Daniel picture Daniel · Dec 19, 2011

Here you go this works for audio sample buffer which is what you are looking at, and if you want to look at the whole process (getting all audio data from MPMediaItem into a file check out this question

CMSampleBufferRef ref=[output copyNextSampleBuffer];
        // NSLog(@"%@",ref);
        if(ref==NULL)
            break;
        //copy data to file
        //read next one
        AudioBufferList audioBufferList;
        NSMutableData *data=[[NSMutableData alloc] init];
        CMBlockBufferRef blockBuffer;
        CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(ref, NULL, &audioBufferList, sizeof(audioBufferList), NULL, NULL, 0, &blockBuffer);
        // NSLog(@"%@",blockBuffer);



        for( int y=0; y<audioBufferList.mNumberBuffers; y++ )
        {
            AudioBuffer audioBuffer = audioBufferList.mBuffers[y];
            Float32 *frame = (Float32*)audioBuffer.mData;


            [data appendBytes:frame length:audioBuffer.mDataByteSize];



        }


        CFRelease(blockBuffer);
        CFRelease(ref);
        ref=NULL;
        blockBuffer=NULL;
        [data release];