使用waveInOpen保存wave文件

时间:2012-07-30 16:23:47

标签: c++ winapi audio wav

我正在尝试使用waveInOpen和co(see here

将声音录制到.wave文件

这是我要记录到缓冲区的代码,它似乎有效:

#include <Windows.h>
#include <MMSystem.h>
#include <iostream>

using namespace std;

int main(){

    HWAVEIN microHandle;
    WAVEHDR waveHeader;

    const int NUMPTS = 22050 * 10;   // 10 seconds
    int sampleRate = 22050;
    short int waveIn[NUMPTS];   // 'short int' is a 16-bit type; I request 16-bit samples below
                                // for 8-bit capture, you'd use 'unsigned char' or 'BYTE' 8-bit types

    MMRESULT result = 0;

    WAVEFORMATEX format;
    format.wFormatTag=WAVE_FORMAT_PCM;      // simple, uncompressed format
    format.wBitsPerSample=8;                //  16 for high quality, 8 for telephone-grade
    format.nChannels=1;                     //  1=mono, 2=stereo
    format.nSamplesPerSec=sampleRate;       //  22050
    format.nAvgBytesPerSec=format.nSamplesPerSec*format.nChannels*format.wBitsPerSample/8;
                                            // = nSamplesPerSec * n.Channels * wBitsPerSample/8
    format.nBlockAlign=format.nChannels*format.wBitsPerSample/8;                    
                                            // = n.Channels * wBitsPerSample/8
    format.cbSize=0;

    result = waveInOpen(&microHandle, WAVE_MAPPER, &format, 0L, 0L, WAVE_FORMAT_DIRECT);

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

    // Set up and prepare header for input
    waveHeader.lpData = (LPSTR)waveIn;
    waveHeader.dwBufferLength = NUMPTS*2;
    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);

     waveInClose(microHandle);

    return 0;
}

但我没有找到关于如何将其保存在磁盘上的任何功能或解释

我应该保存WAVEFORMATEX结构吗?还是有其他东西要添加到wave文件头?

唯一的问题是我只能使用Windows库,我不能安装任何其他的

谢谢:)

1 个答案:

答案 0 :(得分:5)

.WAV文件不仅包含原始数据,还包含格式和额外数据,并且通常包含RIFF structure

MSDN解释写入文件,例如在这里:Writing to a WAV File

此外,当前的Windows SDK \Samples\multimedia\directshow\dmo\dmodemo\dsutil.*文件具有类似CWaveFile类的实现。