为什么录音机代码可以工作8位,但不能工作16位?

时间:2012-08-08 07:03:33

标签: windows audio record

我正在尝试在Windows上录制音频,这是我的代码。它适用于8位,但它不能用于16位。谁能帮我?     #包括     #包括     #包括     #pragma comment(lib,“winmm.lib”)     使用namespace std;

int test(){

    HWAVEIN microHandle;
    WAVEHDR waveHeader;

    MMRESULT result = 0;

    WAVEFORMATEX waveformat;
    waveformat.wFormatTag = WAVE_FORMAT_PCM;

    waveformat.wBitsPerSample=8;
    waveformat.nSamplesPerSec=16000;//8000;
    waveformat.nAvgBytesPerSec=waveformat.nSamplesPerSec*waveformat.nSamplesPerSec/8;

    waveformat.nChannels=1;
    waveformat.nBlockAlign=waveformat.nChannels*waveformat.wBitsPerSample/8;

    waveformat.cbSize=0;

    result = waveInOpen(&microHandle, WAVE_MAPPER, &waveformat, 0L, 0L, CALLBACK_EVENT);

    if (result)
    {
        cout << "Fail step 1" << endl;
        cout << result << endl;
        Sleep(10000);
        return 0; 
    }

    const int BUFSIZE = 16000*4;
    char *  buf = (char *)malloc(BUFSIZE);
    // Set up and prepare header for input
    waveHeader.lpData = (LPSTR)buf;
    waveHeader.dwBufferLength = BUFSIZE;
    waveHeader.dwBytesRecorded=0;
    waveHeader.dwUser = 0L;
    waveHeader.dwFlags = 0L;
    waveHeader.dwLoops = 0L;
    waveInPrepareHeader(microHandle, &waveHeader, sizeof(WAVEHDR));

    // Insert a wave input buffer
    result = waveInAddBuffer(microHandle, &waveHeader, sizeof(WAVEHDR));

    if (result)
    {
        cout << "Fail step 2" << endl;
        cout << result << endl;
        Sleep(10000);
        return 0;
    }

    result = waveInStart(microHandle);

    if (result)
    {
        cout << "Fail step 3" << endl;
        cout << result << endl;
        Sleep(10000);
        return 0;
    }


    // Wait until finished recording
    do {} while (waveInUnprepareHeader(microHandle, &waveHeader, sizeof(WAVEHDR))==WAVERR_STILLPLAYING);

    FILE *fp = fopen("output.pcm","w");
    fwrite(buf,1,BUFSIZE,fp);
    fclose(fp);

    waveInClose(microHandle);

    return 0;
}
void main()
{
    test();
}

如果我设置参数waveformat.wBitsPerSample = 8,它可以正确录制音频, 但如果我将它设置为waveformat.wBitsPerSample = 16,它会记录噪音!!! 任何人都可以帮助我吗?

感谢。

1 个答案:

答案 0 :(得分:0)

它应该是FILE * fp = fopen(“output.pcm”,“wb”); NOT FILE * fp = fopen(“output.pcm”,“w”);