4

我正在使用 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 确实是一些随机的东西。我究竟做错了什么?

4

1 回答 1

3

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

于 2014-05-01T14:02:49.810 回答