I have file which is opened with SF_FORMAT_WAV|SF_FORMAT_FLOAT
but have samples in 24 bit format. Sndfile docs says that the data type used by the calling program and the data format of the file do not need to be the same so using sf_write_int()
i can write 32 bit integer samples and library converts to float on the fly. But what about 24 bit. Do i pack it into int
and then write using sf_write_int()
or something else.
It should be possible to just scale it by 256 to make it 32-bit and use sf_write_int
. If you were expecting libsndfile to do any dithering or something for you this would be a bad idea, but as far as I can tell that's not in its job description.
You have to define the format of your output file to be SF_FORMAT_WAV|SF_FORMAT_PCM_24;
. When you do that, whatever your internal data are ( float
, int16
...), your output file will be written with the requested format.
Here is an example where I read a file (a simple 0.5 second sine at FS of 44100 Hz designed with Audacity) with floating point 32 bit data. My data is also float internally. Then I write a 24 bit PCM file.
#include <stdio.h>
#include <stdlib.h>
#include "sndfile.h"
#define DATA_TO_CONVERT 22050
int main(void)
{
char *inFileName, *outFileName;
SNDFILE *inFile, *outFile;
SF_INFO inFileInfo, outFileInfo;
float dataBuffer[DATA_TO_CONVERT];
// Input file 32 bit float
inFileName = "sine_32.wav";
inFile = sf_open(inFileName, SFM_READ, &inFileInfo);
// Output file 24 bit
outFileName = "sine_24.wav";
outFileInfo.frames = inFileInfo.frames;
outFileInfo.samplerate = inFileInfo.samplerate;
outFileInfo.channels = inFileInfo.channels;
outFileInfo.format = SF_FORMAT_WAV|SF_FORMAT_PCM_24; // Wanted output format
outFile = sf_open(outFileName, SFM_WRITE, &outFileInfo);
sf_read_float(inFile, dataBuffer, DATA_TO_CONVERT);
sf_write_float(outFile, dataBuffer, DATA_TO_CONVERT);
sf_close(inFile);
sf_close(outFile);
// Check Output file
sf_open(outFileName, SFM_READ, &outFileInfo);
printf("Output File format : 0x%x\n", outFileInfo.format);
return 0;
}
The console output is:
Output File format : 0x10003
Which means SF_FORMAT_WAV|SF_FORMAT_PCM_24
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.