I want to write a program in C that will take a .wav file as an input and will output a C array i.e. raw PCM samples. I know the bitrate and have other information about the .wav file beforehand and I just want the PCM samples. The PCM samples are to be loaded on a microcontroller and hence the C array. Where do I start? Please help!!

I can't remember the sample size in WAV files, but I think it is 16 bits, which is a short integer in C. However, the bit order is something you need to determine, just in case you need to re-order the samples before uploading to the microcontroller. IE, this is called the BIG-ENDIAN vs. LITTLE-ENDIAN problem. That's something you would need to research. The C code is pretty simple to stuff the data into an array, and can be done in a single read once you know the size of the file, which you will use to size the array. Example:

FILE* fp = fopen(pathToFile, "r");
size_t sizeOfFile = 0;
char* rawbuffer = 0;
unsigned short int* sampleBuf = 0;
size_t bytesRead = 0;

/* Assume fopen succeeded.*/
fseek(fp, 0L, SEEK_END);
sizeOfFile = (size_t)ftell(fp);
rewind(fp);

rawbuffer = (char*)calloc(sizeOfFile, 1);

/* Assume calloc succeeded - but this may be an issue of the file is really big! */
bytesRead = fread((void*)rawbuffer, 1, sizeOfFile, fp); /* Need error checking here also. */

/* Assume read got all the data, in which case bytesRead == sizeOfFile*/
sampleBuf = (unsigned short int*)rawbuffer;

/* You now have an array of sample-size stuff. */
for (size_t i = 0, j = bytesRead / sizeof(unsigned short int); i < j; i++)
{
    unsigned short int sample = sampleBuf[i];
    /* Now, reorder sample if necessary and send to micro-controller. */
}

Bear in mind that this code is missing a LOT of necessary error checking and other stuff; however, it should suffice as a starting point.

Thanks for your reply rubberman! I have resampled the .wav files to 8 bit 16kHz sampling frequency but I have no idea how to give a wav file as an input to my C program. Thanks again!

You can do that on the command line like this:

#include <stdio.h>
int main(int argc, const char** argv)
{
    const char* pathToFile = 0;
    if (argc != 2)
    {
        fprintf(stderr, "Error - no wav file specified on command line\n");
        exit(1);
    }
    pathToFile = argv[1];

    /* Insert rest of code here */

    /* When finished, return 0 indicating program was successful. */
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.