wav轉txt格式的代碼實現(c,python)


  平時經常做音頻算法,經常用得到wav轉txt的轉換,這里就做個備忘,自己寫了一些小代碼來實現這個目標:

第一個是c代碼的實現:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <math.h>
 4 
 5 #define W 128
 6 
 7 int FileSet = 0;
 8 int FileEnd = 0;
 9 int FileLength = 0;
10 short InputData[W];
11 void buf_txt(short *buf,int len,FILE*ttt)
12 {
13     for(int i=0; i < len; i++)
14     {   
15         fprintf(ttt, ",%d",buf[i]);
16         if(i % 64 == 0)
17         {   
18             fprintf(ttt, "\n");
19         }   
20     }   
21 }
22 
23 int main(int argc, char** argv)
24 {
25 
26     FILE *Ifp,*ttt;
27         
28     if(argc != 2)
29     {   
30         printf("usage:./wav2txt XX.wav EEE.txt\n\t");
31         return 0;
32     }   
33 
34     Ifp = fopen(argv[1],"rb");
35 
36     ttt = fopen(argv[2],"w");
37 
38     fseek(Ifp,0L,SEEK_END);
39     FileEnd=ftell(Ifp);
40     rewind(Ifp);
41     FileLength = FileEnd/2;
42 
43     while(FileLength >= W)
44     {   
45         fread(InputData,sizeof(short),W,Ifp);
46         buf_txt(InputData,W,ttt);
47         FileLength -= W;
48         
49     }   
50 
51     fread(InputData,sizeof(short),FileLength,Ifp);
52 
53     buf_txt(InputData,FileLength,ttt);
54 
55     return 0;
56 }
57 ~    

  

第二個是python的代碼:

 

 1 # -*- coding: utf-8 -*-
 2 import wave
 3 import matplotlib.pyplot as plt 
 4 import numpy as np
 5 import sys
 6 
 7 
 8 f = wave.open(sys.argv[1], 'rb' )
 9 params = f.getparams()
10 nchannels, sampwidth, framerate, nframes = params[:4]
11 
12 np.set_printoptions(threshold='nan')
13 
14 Data_str = f.readframes(nframes)
15 Data_num = np.fromstring(Data_str,dtype=np.int16)
16 print(Data_num)
17 print(nframes)
18 
19 #np.savetxt("test.txt",Data_num)
20 
21 fw =file(sys.argv[2],"w")
22 fw.write(str(list(Data_num)))
23 fw.close()
24 
25 f.close()

 

python和c代碼放在一起的時候,才會發現,它是多么的簡潔,看來以后要經常使用了。把python作為一個重點使用的語言來重視起來。

 

 備忘問題:

1 一個數組無窮大,numpy在輸出時會自動省略中間部分而只打印部分。

  解決方法:使用numpy.set_printoptions(threshold='nan')

2 Python中list里面的元素沒有以逗號為分割,而是以空格為分割:

 解決方法:基礎知識不夠牢固,list中元素是以逗號做分割的,matrix中是以空格為分割的,強轉即可。

參考文檔:

1 https://www.cnblogs.com/dupuleng/articles/5028291.html

2 https://blog.csdn.net/bowean/article/details/80868965


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM