既然生成聲音已經沒問題了,現在簡單生成一下一個類似蜂鳴器的隨機音樂文件。(注:可能書寫有格式不正式之類問題,反正思路應該沒問題,測試可以運行) 因為是隨機,那麼先弄個產生隨機數的類 R.H和R.CPP R.H: 復制代碼 #ifndef R_H_ #define R_H_ class R{ public: R(); int suiji(int i); int suiji(); private: int shuchu(int number); }; #endif /* R_H_ */ 復制代碼 R.cpp: 復制代碼 #include <windows.h> #include<iostream> #include <cstdlib> #include"R.h" using namespace std; R::R(){ int i=GetTickCount(); cout<<i<<endl; srand(i); } int R::suiji(int i){ return shuchu(i); } int R::suiji(){ return shuchu(8); } int R::shuchu(int number){ if(number>1000) number=1000; int jieguo; jieguo=rand()%number; return jieguo; } 復制代碼 也就是可以通過R r 和r.suiji();來生成一個隨機數 接下來是生成WAV文件的頭文件Head.h和Head.cpp Head.h:基本上是還是按照上篇文章的格式,不過把一些東西封裝起來, 復制代碼 #ifndef HEAD_H_ #define HEAD_H_ class Head{ public: Head(); void setsize(int); long int getsa(); long int getsize(); ~Head(); private: char RIFF[4]; long int size0; char WAVE[4]; char FMT[4]; long int size1; short int fmttag; short int channel; long int samplespersec; long int bytepersec; short int blockalign; short int bitpersamples; char DATA[4]; long int size2; }; #endif /* HEAD_H_ */ 復制代碼 Head.cpp:基本配置還是按照原來上一篇文章那個 復制代碼 #include "Head.h" #include<iostream> using namespace std; Head::Head(){ strcpy(RIFF,"RIFF"); size0=0; strcpy(WAVE,"WAVE"); strcpy(FMT,"fmt "); size1=16; fmttag=1; channel=1; samplespersec=11025; bytepersec=11025; blockalign=1; bitpersamples=8; strcpy(DATA,"data"); size2=0; cout<<RIFF<<size0<<WAVE<<endl; } Head::~Head(){ cout<<生成完成<<endl; } void Head::setsize(int size){ Head::size0=size+24; Head::size2=size; } long int Head::getsa(){ return Head::samplespersec; } long int Head::getsize(){ return Head::size2; } 復制代碼 最後就是主文件了,main.cpp: 基本方法比較簡單,dou[8]存的是C大調的dou ruai mi fa ...到高音dou的頻率。因為一秒采樣是11025(上面設的),那麼pai存放的就是1/4時間的采樣個數。 然後設總采樣數44100,也就是4秒鐘,同時將數據大小確定為44100,接下去和上一篇大同小異,就開始生成了。 復制代碼 #include <iostream> #include<fstream> #include"Head.h" #include<math.h> #include"R.h" using namespace std; int dou[8]={262,294,330,349,392,440,494,524}; int pai=11025/4; void runrun(){ Head head; R r; head.setsize(44100); char body[head.getsize()]; int i,i2; for(i2=0;i2<16;i2++) { int b=r.suiji(7); for(i=0;i<pai;i++){ float a=(head.getsa()/dou[b]); body[i+i2*pai]=(int)(64*sin(6.28/a*i)+128); cout<<a<<b<<endl; } } ofstream ocout; ocout.open("1213.wav",ios::out|ios::binary); ocout.write((char*)&head,sizeof head); ocout.write((char*)&body,sizeof body); ocout.close(); cout <<head.getsize() <<" "<<dou[0]<<endl; } int main() { runrun(); return 0; }