我尝试写一个音调发生器。我只是想输出一个440Hz的正弦波,这种方法很有效,但每当我更新缓冲区时我都会听到咔哒声(我猜)。
这是我的更新代码:
HANDLE hEvent[2];
hEvent[0] = CreateEvent(NULL, FALSE, FALSE, L"NOTIFY0");
hEvent[1] = CreateEvent(NULL, FALSE, FALSE, L"NOTIFY1");
LPDIRECTSOUNDNOTIFY8 lpDsNotify;
DSBPOSITIONNOTIFY PositionNotify[2];
HRESULT hr;
if (SUCCEEDED(
hr = lpDsbSecondary->QueryInterface(IID_IDirectSoundNotify8,
(LPVOID*)&lpDsNotify)))
{
PositionNotify[0].dwOffset = 0;
PositionNotify[0].hEventNotify = hMyEvent[0];
PositionNotify[1].dwOffset = 5000;
PositionNotify[1].hEventNotify = hMyEvent[1];
hr = lpDsNotify->SetNotificationPositions(2, PositionNotify);
lpDsNotify->Release();
}
long time = 0;
short* waveData = new short[5000];
m_secondaryBuffer1->SetCurrentPosition(0);
m_secondaryBuffer1->SetVolume(DSBVOLUME_MAX);
m_secondaryBuffer1->Play(0, 0, DSBPLAY_LOOPING);
while (true)
{
HRESULT hr = WaitForMultipleObjects(2, hEvent, FALSE, 0);
if (hr == WAIT_OBJECT_0)
{
for (int x = 0; x<5000; x++)
{
waveData[x] = createWave(time, 440.0f);
time++;
}
IFA->UpdateBufferData(&(m_secondaryBuffer1), 5000, waveData, 5000);
}
if (hr == WAIT_OBJECT_0 + 1)
{
for (int x = 0; x<5000; x++)
{
waveData[x] = createWave(time, 440.0f);
time++;
}
IFA->UpdateBufferData(&(m_secondaryBuffer1), 0, waveData, 5000);
}
}
创建二级缓冲区:
int error;
FILE* filePtr;
unsigned int count;
WaveHeaderType waveFileHeader;
WAVEFORMATEX waveFormat;
DSBUFFERDESC bufferDesc;
HRESULT result;
IDirectSoundBuffer* tempBuffer;
unsigned char* bufferPtr;
unsigned long bufferSize;
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nSamplesPerSec = 44100;
waveFormat.wBitsPerSample = 16;
waveFormat.nChannels = 1;
waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
waveFormat.cbSize = 0;
bufferDesc.dwSize = sizeof(DSBUFFERDESC);
bufferDesc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_GLOBALFOCUS | DSBCAPS_CTRLPOSITIONNOTIFY;
bufferDesc.dwBufferBytes = 100000;
bufferDesc.dwReserved = 0;
bufferDesc.lpwfxFormat = &waveFormat;
bufferDesc.guid3DAlgorithm = GUID_NULL;
result = m_DirectSound->CreateSoundBuffer(&bufferDesc, &tempBuffer, NULL);
if(FAILED(result)) return;
result = tempBuffer->QueryInterface(IID_IDirectSoundBuffer8, (void**)&*secondaryBuffer);
if(FAILED(result)) return;
tempBuffer->Release();
tempBuffer = 0;
这是createWave:
short waveSIN(int x, float frequency)
{
return (short)(32767.0f * sinf(frequency * 2.0f * M_PI * ( ( float ) x / 44100.0f ) ));
}
我做错了什么?