1

I'm writing a piece of code in C for pocketsphinx module of freeswitch to save the utterance (waveform or audio) to a file. I receive the audio as a void *data and its unsigned int len and I have to save it as a RAW (or PCM) file (no headers). How do I do this?

I've tried this:

FILE *_file;
int16_t *_data;
_data = (int16_t *) data;
_file=fopen("utterance","ab");
fwrite(data, sizeof(_data[0]), sizeof(_data)/sizeof(_data[0]), _file);
fclose(_file);
_file=NULL;

It doesn't work (Maybe I'm not doing it right?). I've also found libvlc and libsndfile but haven't found any function that'd serve me. Anyone here have a simple example/tutorial on this?

I'm working on C, VS2010, Win8.1 (x64)

MSalters
  • 173,980
  • 10
  • 155
  • 350
codedrunk
  • 43
  • 7

3 Answers3

1

you shouldn't use sizeof(_data)/sizeof(_data[0]) when _data is a pointer; sizeof(_data) is how many bytes the pointer _data takes

size_t valueCount = sampleCount * channelCount;
FILE *_file;
int16_t *_data;
_data = (int16_t *) data;
_file=fopen("utterance","ab");
fwrite(data, sizeof(_data[0]), valueCount, _file);
fclose(_file);
_file=NULL;

you could also use

fwrite(data, 1, len, _file);
programmerjake
  • 1,794
  • 11
  • 15
  • I can't believe how I missed that. I used `fwrite(data, 1, len, _file);` and it's working. Thanks a ton Jake, for fast and accurate reply! – codedrunk Aug 07 '14 at 17:30
0

The major issue with this is that you use sizeof(_data) / sizeof(_data[0]) as an attempt to compute the length of the array. However, since _data is of type int16_t *, i.e. just a pointer, then sizeof(_data) will return the size of a pointer (which, in your case, is just 8). You'll need some other way to pass in the length of the array.

Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
0

sizeof applied to a pointer does not tell you how much memory there is "behind it" (the pointer doesn't know whether it's pointing at one lonely thing, or at the first element of an array).
Instead it tells you the size, measured in chars, of a pointer, which is usually 4 or 8 these days.

Since you know where the data is (data) and how much there is of it (len), you don't need to cast or calculate anything.

Use either

fwrite(data, 1, len, _file);

or

fwrite(data, len, 1, _file);
molbdnilo
  • 64,751
  • 3
  • 43
  • 82