如何从libsndfile库中读取数组格式的音频文件,如MATLAB的audioread

时间:2016-03-07 23:55:42

标签: c++ matlab audio speech-recognition audio-recording

我正在使用libsndfile来读取.caf文件。我能够正确读取音频文件中的项目数。但是,当我将这些数字保存在文本文件中并尝试使用MATLAB验证我的值时,它们看起来有很大不同。我已经用C ++和我从C ++和MATLAB获得的值附加了代码。

void ofApp::setup(){


const char* fn = "/Users/faiyadhshahid/Desktop/Desktopdemo.caf";

SNDFILE *sf;
SF_INFO info;
int num_channels, num, num_items, *buf, f, sr,c, i , j;
FILE *out;

/* Open the WAV file. */
info.format = 0;
sf = sf_open(fn,SFM_READ,&info);
if (sf == NULL)
{
    printf("Failed to open the file.\n");
}

/* Print some of the info, and figure out how much data to read. */
f = info.frames;
sr = info.samplerate;
c = info.channels;
printf("frames=%d\n",f);
printf("samplerate=%d\n",sr);
printf("channels=%d\n",c);
num_items = f*c;
printf("num_items=%d\n",num_items);

/* Allocate space for the data to be read, then read it. */
buf = (int *) malloc(num_items*sizeof(int));
num = sf_read_int(sf,buf,num_items);
sf_close(sf);
printf("Read %d items\n",num);
/* Write the data to filedata.out. */
out = fopen("/Users/faiyadhshahid/Desktop/filedata.txt","w");
for (i = 0; i < num; i += c)
{
    for (j = 0; j < c; ++j)
        fprintf(out,"%d ",buf[i+j]);
    fprintf(out,"\n");
}
fclose(out);
return 0;

}

Values of C++ (on left) vs MATLAB (on right):

1 个答案:

答案 0 :(得分:0)

我自己想通了。我正在比较苹果和橘子。 我需要做的更改是将缓冲区转换为保存值以读取浮点值。 `int num_channels,num,num_items,f,sr,c,i,j;     float * buf;     FILE * out;

/* Open the WAV file. */
info.format = 0;
sf = sf_open(fn,SFM_READ,&info);
if (sf == NULL)
{
    printf("Failed to open the file.\n");
}

/* Print some of the info, and figure out how much data to read. */
f = info.frames;
sr = info.samplerate;
c = info.channels;
printf("frames=%d\n",f);
printf("samplerate=%d\n",sr);
printf("channels=%d\n",c);
num_items = f*c;
printf("num_items=%d\n",num_items);

/* Allocate space for the data to be read, then read it. */
buf = (float *) malloc(num_items*sizeof(float));
num = sf_read_float(sf,buf,num_items);
sf_close(sf);
printf("Read %d items\n",num);
/* Write the data to filedata.out. */
out = fopen("/Users/faiyadhshahid/Desktop/filedata.txt","w");
for (i = 0; i < num; i += c)
{
    for (j = 0; j < c; ++j)
         fprintf(out,"%f \n",buf[i]);
            // fprintf(out,"\n");
}
fclose(out);

`