Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert CMSampleBufferRef to NSData

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.

like image 294
RyanM Avatar asked Dec 18 '11 18:12

RyanM


1 Answers

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];
like image 144
Daniel Avatar answered Oct 22 '22 04:10

Daniel