我有一个问题:音频块播放完毕后,我不会收到“ MM_WOM_DONE”。

与声音有关的代码:

void initSound(HWND hwnd) {
    HWAVEOUT hWaveOut;
    WAVEFORMATEX wfx;

    wfx.nSamplesPerSec = 44100; /* sample rate */
    wfx.wBitsPerSample = 8; /* sample size */
    wfx.nChannels = 1; /* channels*/

    wfx.cbSize = 0;
    wfx.wFormatTag = WAVE_FORMAT_PCM;
    wfx.nBlockAlign = (wfx.wBitsPerSample >> 3) * wfx.nChannels;
    wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec;

    if(waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfx, (DWORD)hwnd, 0, CALLBACK_WINDOW) != MMSYSERR_NOERROR) {
        printf("Wave out can't be opened!\n");
        ExitProcess(1);
    } else {
        printf("Wave out is now open!\n");
    }

    /* Building a block */
    DWORD size = 8192;
    int frequency = 523; // C note
    int volume = 20;
    float sinMul = 3.1415 * frequency / (wfx.nSamplesPerSec);
    unsigned char blockArray[size];
    for (int i = 0; i < size; i++) {
        blockArray[i] = 128 + (signed char)(sin(i * sinMul) * volume);
    }

    WAVEHDR header;
    ZeroMemory(&header, sizeof(WAVEHDR));
    header.dwBufferLength = size;
    header.lpData = (LPSTR)&blockArray;
    printf("Block was created!\n");

    /* Prepearing header */
    printf("Prepearing header for wave out...\n");
    waveOutPrepareHeader(hWaveOut, &header, sizeof(WAVEHDR));

    /* Playing a block */
    printf("Writing sound to wave out...\n");
    waveOutWrite(hWaveOut, &header, sizeof(WAVEHDR));
    printf("Waiting sound for finishing playing...\n");
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch(msg) {
        case WM_CREATE:
            initSound(hwnd);
        break;
        case MM_WOM_DONE:
            printf("Sine wave stopped playing!");
            waveOutUnprepareHeader((HWAVEOUT)wParam, (LPWAVEHDR)lParam, sizeof(WAVEHDR));
            waveOutClose((HWAVEOUT)wParam);
        break;
    }
}


控制台输出:

Wave out is now open!
Block was created!
Prepearing header for wave out...
Writing sound to wave out...
Waiting sound for finishing playing...


正弦波播放良好且正确,但是一旦播放完毕,就会在短时间内(将近100-200 ms)开始播放一些短白噪声。另外,“正弦波停止播放!”该消息永远不会出现在控制台中,这意味着永远不会使用“ MM_WOM_DONE”消息来调用WndProc函数。如果我处理“ initSound”函数中的所有内容,即使写入和关闭waveOut之间的延迟更大(超过一秒),正弦波最终也不会产生白噪声。

最佳答案

对于解决此问题的贡献归功于Remy Lebeau。我做的错误是将wave头和wave头存储在堆栈中而不是堆中。这导致出现噪音,因为数据被覆盖并且声卡开始读取无效数据。 Wave out标头也可能丢失或被覆盖,因此我无法正确调用MM_WOM_DONE消息。只需在函数外部声明变量即可解决所有这些问题。像这样:

HWAVEOUT hWaveOut;
WAVEFORMATEX wfx;
DWORD size = 8192;
WAVEHDR header;

void initSound(HWND hwnd) {
    /* Body of function */
}


因此,如果您遇到此问题,请确保与waveout相关的变量的寿命足够长。

关于c - 消息“MM_WOM_DONE”未被调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59642472/

10-11 22:05