How to convert CMSampleBufferRef to NSData
Asked Answered
H

1

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.

Hamamatsu answered 18/12, 2011 at 18:54 Comment(0)
M
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];
Milore answered 18/12, 2011 at 23:52 Comment(6)
Thanks a lot Daniel! Worked like a charm :)Hamamatsu
I'm still a bit lost and very noob on this stuff. What is 'output' defined to be?Recusant
@Recusant Check the link i provide in the second line (its a full solution not just a fragment), output is AVAssetReaderOutputMilore
How to convert video samples to NSData?Deraign
@Deraign it does that in the for loopMilore
AudioBuffer is for audio right. its ok. I think I found a way. can you please look into this #61078836 and let me know if anything is missing. Bugging my mind for the last few days. couldn't find anything related to it online.Deraign

© 2022 - 2024 — McMap. All rights reserved.