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

Posted

技术标签:

【中文标题】如何从 MATLAB 的 audioread 等 libsndfile 库中读取数组格式的音频文件【英文标题】:How to read an audio file in an array format from libsndfile library like MATLAB's audioread 【发布时间】:2016-03-07 23:55:42 【问题描述】:

我正在使用 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):

【问题讨论】:

请注意在 matlab 中您的数字非常小。 0.00021.... 不可能是int,那么为什么要与int 比较呢?看起来您还有一些工作要做,以便将两个数据集放入相同的单元中。 【参考方案1】:

我自己想出来的。我在比较苹果和橙子。 我需要做的更改是将保存值的缓冲区转换为读取浮点值。 `int num_channels,num,num_items,f,sr,c,i,j; 浮动 *buf; 文件 *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);

`

【讨论】:

得说这比我预期的要简单。我想这更像是读入,然后应用 y=mx+b

以上是关于如何从 MATLAB 的 audioread 等 libsndfile 库中读取数组格式的音频文件的主要内容,如果未能解决你的问题,请参考以下文章

MATLAB里函数audioread的使用方法有哪些?

如何在 Python 中读取类似于 Matlab audioread 的音频文件?

MATLAB audioread - 从单元格中的struct调用一个.wav文件时出现问题

matlab之“audioread”函数帮助文档翻译

wav文件和FFT的matlab中的Audioread

matlab 使用 audioread sound 读取和播放 wav 文件