DirectSound:简单的pcm播放

时间:2012-04-23 13:21:23

标签: c++ winapi directsound

我正在玩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实际上是一些随机的东西。我做错了什么?

1 个答案:

答案 0 :(得分:2)

我有一些问题,我通过将buf_format.dwFlags设置为来修复您的代码 buf_format.dwFlags = DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GETCURRENTPOSITION2 |DSBCAPS_GLOBALFOCUS | DSBCAPS_LOCSOFTWARE | DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_CTRLVOLUME | DSBCAPS_GETCURRENTPOSITION2;