Search code examples
objective-cxcodearrayswavlame

xcode, objective c, read contents of audio (.WAV, PCM encoded) file into a C integer array


I am working on an app that captures an audio recording and converts it into mp3.

i am using the LAME open source library in C to convert into mp3. it has a function which requires the entire stream of integers representing the PCM encoded .wav file as an integer array.

This is my first project ever on iphone development and I am not able to figure out how can i read the contents of the wav file (which is supposed to be nothing but stream of integers) into a C style array?

please help.

Neerav


Solution

  • In Objective C, you can easily read from a file into an NSData object with something like this:

    NSData *data = [NSData datawithContentsOFFile:filename];
    

    You can then get the number of bytes in that object and allocate a C style integer array of matching size like this:

    NSUInteger length = [data length];
    int *cdata = (int*)malloc(length);
    

    and copy the bytes out of the NSData object into the C array like this:

    [data getBytes:(void*)cdata length:length];
    

    Don't forget to free the memory in the C array when you're done with it.

    free(cdata);