我正在玩DirectSound,并尝试使用以下代码播放简单的随机wav数据:

int _tmain(int argc, _TCHAR* argv[])
{
    LPDIRECTSOUND8 dsound;
    WAVEFORMATEX format;
    const int numchunks = 8;
    LPDIRECTSOUNDBUFFER dsbuf;
    DSBUFFERDESC buf_format;
    const int chunksize = 1024;
    HRESULT res;
    uint8_t *data1,*data2;
    uint32_t size1,size2;

    memset(&format,0,sizeof(WAVEFORMATEX));

    format.wFormatTag = WAVE_FORMAT_PCM;
    format.nChannels  = 1;
    format.wBitsPerSample = 16;
    format.nSamplesPerSec = 44100;
    format.nBlockAlign = format.nChannels * format.wBitsPerSample / 8;
    format.nAvgBytesPerSec = format.nBlockAlign * format.nSamplesPerSec ;
    format.cbSize = 0;

    assert(DirectSoundCreate8(NULL,&dsound,NULL) == DS_OK);


    assert(dsound->SetCooperativeLevel(GetDesktopWindow(),DSSCL_PRIORITY) == DS_OK);


    memset(&buf_format,0,sizeof(DSBUFFERDESC));
    buf_format.dwSize = sizeof(buf_format);
    buf_format.dwFlags = DSBCAPS_GETCURRENTPOSITION2;
    buf_format.dwFlags |= DSBCAPS_STICKYFOCUS;
    buf_format.dwBufferBytes = numchunks * chunksize;
    buf_format.dwReserved = 0;
    buf_format.lpwfxFormat = &format;


    res = dsound->CreateSoundBuffer(&buf_format,&dsbuf,NULL);
    assert(res == DS_OK );

    srand(time(NULL));

    assert(IDirectSoundBuffer_Lock(dsbuf,0,buf_format.dwBufferBytes,(LPVOID *)&data1,(LPDWORD)&size1,
                            (LPVOID *)&data2,(LPDWORD)&size2,DSBLOCK_ENTIREBUFFER) == DS_OK);

    cout << "got buffer with size "<<size1<<endl;

    for (uint32_t i = 0 ; i < size1; i ++)
        data1[i] = rand() % 256;

    IDirectSoundBuffer_Unlock(dsbuf,
                                  (LPVOID) data1, (DWORD)size1,
                                  (LPVOID) data2, (DWORD)size2);

    assert(IDirectSoundBuffer_Play(dsbuf,0,0,DSBPLAY_LOOPING) == DS_OK);


    cin.get();

    return 0;
}

但是在输出时,我只听到沉默。另外,输出没有错误,我的data1实际上是一些随机的东西。我究竟做错了什么?

最佳答案

我遇到了某种问题,并通过将buf_format.dwFlags设置为来修复了您的代码buf_format.dwFlags = DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GETCURRENTPOSITION2 |DSBCAPS_GLOBALFOCUS | DSBCAPS_LOCSOFTWARE | DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_CTRLVOLUME | DSBCAPS_GETCURRENTPOSITION2;

10-08 08:21