Search code examples
objective-ciosnsmutabledata

Saving and retrieving Sint16 from NSMutableData


I need somewhere to save and then to retrieve Sint16 (2 bytes).

I get:

SInt16* frames = (SInt16*)inBuffer->mAudioData;

and want to save &frames[i] somewhere (NSMutableData?) that could later easily retrieve. I tried to save like this (in cycle):

[recordedData appendBytes:&frames[i] length:1];

and retrieve:

    SInt16* framesRetrieve ;

    //sets up mybytes buffer and reads in data from myData
    framesRetrieve = (SInt16*)malloc([mutableData framesRetrieve]);

    [mutableData getBytes:framesRetrieve];

But this return not the same as i put into.

So what could be a solution ?

thanks.


Solution

  • You need to know the length of the data and then you can store the whole buffer in an NSMutableData object:

    To store:

    SInt16 *frames = ...;
    NSUInteger length = ...;    // Assuming number of elements in frames, not bytes!   
    NSMutableData *data = [[NSMutableData alloc] initWithCapacity:0];
    [data appendBytes:(const void *)frames length:length * sizeof(SInt16)];
    

    To retrieve:

    SInt16 *frames = (SInt16 *)[data bytes];
    NSUInteger length = [data length] / sizeof(SInt16);