在学算法时,每次用wav文件,都是直接跳过文件头,提前写好采样率和文件长度等信息,其实可以使用sndfile.h来解析。今天来记录使用方法。
库文件的准备
注意:sndfile的dll库分32bit和64bit
最简单的查找sndfile的dll库的方法是直接在自己电脑里搜sndfile.h,一般都会搜到,因为可能你有些已安装的软件中用到了这个库,如果没有,就在libsndfile官方网站下载。
C测试代码
在配置属性–》链接器–》输入–》附加依赖项中添加libsndfile-1.lib;
将libsndfile-1.dll放在当前项目目录中。
测试代码如下:
#include <stdio.h>
#include <stdlib.h>
#include "sndfile.h"
int main(int argc, char *argv[])
{
SF_INFO sf_info;
SNDFILE *snd_file;
SNDFILE *fpOut;
SF_INFO sf_info_out;
short *buf1;
sf_count_t cout;
sf_info.format = 0;
snd_file = sf_open(argv[1], SFM_READ, &sf_info);
printf("Using %s.\n", sf_version_string());
printf("File Name : %s\n", argv[1]);
printf("Sample Rate : %d\n", sf_info.samplerate);
printf("Channels : %d\n", sf_info.channels);
printf("Sections : %d\n", sf_info.sections);
printf("Frames : %d\n", (int)sf_info.frames);
buf1 = (short *)malloc(sf_info.frames * sizeof(short) * 2);
sf_info_out.channels = sf_info.channels;
sf_info_out.samplerate = sf_info.samplerate;
sf_info_out.frames = sf_info.frames;
sf_info_out.format = (SF_FORMAT_WAV | SF_FORMAT_PCM_16 | SF_ENDIAN_LITTLE);
fpOut = sf_open(argv[2], SFM_WRITE, &sf_info_out);
if (fpOut == NULL)
{
printf("open out file failed\n");
exit(1);
}
while (sf_read_short(snd_file, buf1, 480) == 480)
{
sf_write_short(fpOut, buf1, 480);
}
free(buf1);
sf_close(snd_file);
sf_close(fpOut);
return 0;
}
参考来源文件
感谢博客原作者的工作。
libsndfile动态库在VS2010下面的调用