2016-03-07 22 views
1

我正在使用libsndfile讀取.caf文件。我能夠通過音頻文件中的項目數量正確讀取文件。但是,當我將這些數字保存在文本文件中並嘗試使用MATLAB驗證我的值時,它們看起來很不一樣。我已經附加了C++中的代碼以及從C++和MATLAB獲得的值。如何從libsndfile庫中讀取數組格式的音頻文件,如MATLAB的audioread

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):

+0

注意如何在Matlab你有一個非常小的數目。 0.00021 ....沒辦法,這是'int',那爲什麼要和'int'比較呢?看起來你有一些工作要將兩個數據集合放到同一個單元中。 – user4581301

+0

是的。你是對的。 – Nasiba

回答

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); 

`

+0

得說這比我想象的要簡單。我認爲它會更像是讀入,然後應用y = mx + b – user4581301

相關問題