暂时记录。
感觉想写个电子钢琴乐程序了,不过感觉音有点怪怪的。
#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 i = 0; i < 8; i++) { GenAudio(aData, scale[i]); for (int j = 0; j < RATE; j++) waveOutWrite(hWavO, &wavehdr, sizeof(wavehdr)); } } waveOutClose(hWavO); waveOutUnprepareHeader(hWavO, &wavehdr, sizeof(wavehdr)); delete[] aData; return 0; }