其他分享
首页 > 其他分享> > win api + 基础乐理产生正弦波声音

win api + 基础乐理产生正弦波声音

作者:互联网

  暂时记录。

  感觉想写个电子钢琴乐程序了,不过感觉音有点怪怪的。

#include <iostream>
#include <windows.h>
#include <Mmreg.h>
#include <mmeapi.h>
#include <Windows.h>
#include <math.h>

#define RATE 44100
#define PIPE 2
#define BUFF (RATE * 500)
#define PI 3.14159

void GenAudio(PBYTE pB, int freq)
{
	double w = (2 * PI) / freq;
	for (int i = 0; i < BUFF; i++)
	{
		pB[i] = 127 + 127 * std::sin(w * i);
	}
}

int main()
{
	WAVEHDR wavehdr;
	WAVEFORMATEX waveformat;
	HWAVEOUT hWavO;
	PBYTE aData = new BYTE[BUFF];
	ZeroMemory(aData, BUFF);

	waveformat.wFormatTag = WAVE_FORMAT_PCM;
	waveformat.nSamplesPerSec = RATE;
	waveformat.nChannels = PIPE;
	waveformat.wBitsPerSample = 16;
	waveformat.nBlockAlign = PIPE * waveformat.wBitsPerSample / 8;
	waveformat.nAvgBytesPerSec = waveformat.nSamplesPerSec * waveformat.nBlockAlign;
	waveformat.cbSize = 0;

	wavehdr.lpData = (LPSTR)aData;
	wavehdr.dwBufferLength = BUFF;
	wavehdr.dwLoops = 1;
	wavehdr.dwFlags = 0;

	if (waveOutOpen(&hWavO, WAVE_MAPPER, &waveformat, NULL, 0, CALLBACK_NULL) != MMSYSERR_NOERROR)
		std::cout << "出错";

	waveOutPrepareHeader(hWavO, &wavehdr, sizeof(wavehdr));

	int scale[] = { 261, 293, 329, 349, 391, 440, 493, 523 };
	

	for (;;)
	{
		for (int i = 0; i < 8; i++)
		{
			GenAudio(aData, scale[i]);
			for (int j = 0; j < RATE; j++)
				waveOutWrite(hWavO, &wavehdr, sizeof(wavehdr));
		}
	}

	waveOutUnprepareHeader(hWavO, &wavehdr, sizeof(wavehdr));
	waveOutClose(hWavO);
	delete[] aData;

	return 0;
}

  

标签:waveformat,wavehdr,win,define,int,api,乐理,include,BUFF
来源: https://www.cnblogs.com/darkchii/p/11883233.html