11

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.

Community
  • 1
  • 1
RyanM
  • 4,474
  • 4
  • 37
  • 44

1 Answers1

10

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];
Community
  • 1
  • 1
Daniel
  • 22,363
  • 9
  • 64
  • 71
  • Thanks a lot Daniel! Worked like a charm :) – RyanM Jan 15 '12 at 19:24
  • I'm still a bit lost and very noob on this stuff. What is 'output' defined to be? – jangelo42 Feb 07 '13 at 00:25
  • @jangelo42 Check the link i provide in the second line (its a full solution not just a fragment), output is AVAssetReaderOutput – Daniel Feb 07 '13 at 16:37
  • How to convert video samples to `NSData`? – prabhu Apr 02 '20 at 11:18
  • @prabhu it does that in the for loop – Daniel Apr 07 '20 at 14:04
  • `AudioBuffer` is for audio right. its ok. I think I found a way. can you please look into this https://stackoverflow.com/questions/61078336/cmsamplebuffergetdatabuffer-returns-nil-value-cocoa-swift and let me know if anything is missing. Bugging my mind for the last few days. couldn't find anything related to it online. – prabhu Apr 07 '20 at 14:20