win api + produce sine sound basis of Music

  Temporarily record.

  Feeling wanted to write electronic piano music program, but feels a bit strange sound.

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

#pragma comment(lib, "Winmm.lib")

#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 a = 0; a <8; a ++) 
		{ 
			Ge and Audio (Data scale [a]); 
			for (j = 0 Int; j <Karate; j ++) 
				of the O utWrite (theirs & wavehdr, sizeof (wavehdr)); 
		} 
	} 

	WaveOutUnprepareHeader (theirs & wavehdr, sizeof (wavehdr)); 
	One of the utClose (late); 
	delete [] data; 

	return 0; 
}

  

Guess you like

Origin www.cnblogs.com/darkchii/p/11883233.html