首页 > 代码库 > C++生成简单WAV文件(二)

C++生成简单WAV文件(二)

既然生成声音已经没问题了,现在简单生成一下一个类似蜂鸣器的随机音乐文件。(注:可能书写有格式不正式之类问题,反正思路应该没问题,测试可以运行)

因为是随机,那么先弄个产生随机数的类 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;}

通过测试运行,觉得这个产生的声音比蜂鸣器更好听一点,而且没有间隔,还是有点旋律的感觉了。生成的文件保存在http://files.cnblogs.com/shibuliao/1213.rar