正弦函数如何变成声音

下面有一个例子,或以帮助大家更好的理解正弦函数如何变成声音,有兴趣的朋友可以把它拷到编译器中运行。它会生成一个44100采样,单声道、16位格式的PCM文件new.pcm,可以用cooledit进行播放!
 
#include <math.h>
#include <iostream>
 
#pragma warning(disable:4996)
#pragma warning(disable:4244)
 
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
 
    int sample_rate = 44100;
    double step = atan(1.0)*8/sample_rate;  // 2*pi/44100
    int sample_scale = (int)pow(2.0,16-1);  // 2^15
    FILE *pFile = fopen("new.pcm","wb");
 
    double t = 0.0;
    double sample;
 
    // 生成10秒数据
    for(int s = 0; s < sample_rate*10; s )
    {
        sample = 0;
 
//        sample = (sin(t) cos(20*t) sin(30*t)*cos(t*40) sin(t*50) cos(t*600) sin(t*125) sin(t*87))/6;
        double x = min(sin(t),cos(t));
        double y = max(300 200*cos(t),300 200*sin(t));
        double z = max(300 200*cos(t*1.5),300 200*sin(t*1.7));
 
        sample = (tan(t*2)*sin(x*y*600)*abs(sin(t/10))*abs(cos(t/5)))*0.2;
        sample = abs(sin(t*10))*sin(x*y)*0.45;
        sample = sin(sin(z*t*0.1))*0.15;
 
        short nSample = sample*sample_scale;
        fwrite(&nSample,1,2,pFile); 
        fflush(pFile);
 
//        printf("s=%d\n",s);
        t = step;
    }
    fclose(pFile);
return 0;
}

本文来自于icoolmedia(314138065),欢迎转 载!
 

 

你可能感兴趣的:(正弦函数如何变成声音)