尝试编写通过WinAPI录制和播放声音的函数

时间:2014-02-12 22:26:43

标签: c winapi voice-recording

我正在尝试在C中创建2个函数:

  • 录制麦克风X秒的一个
  • 获取录音并将其播放给用户的人

这就是我写的:

#include <iostream>
#include <Windows.h>
using namespace std;

#pragma comment(lib, "winmm.lib")

WAVEHDR StartRecord(int seconds)
{
const int NUMPTS = 44100 * seconds;
int sampleRate = 44100;
short int *waveIn = new short int[NUMPTS];

HWAVEIN hWaveIn;
WAVEHDR WaveInHdr;
MMRESULT result;

WAVEFORMATEX pFormat;
pFormat.wFormatTag = WAVE_FORMAT_PCM;
pFormat.nChannels = 1;
pFormat.nSamplesPerSec = sampleRate;
pFormat.nAvgBytesPerSec = 2 * sampleRate;
pFormat.nBlockAlign = 2;
pFormat.wBitsPerSample = 16;
pFormat.cbSize = 0;

result = waveInOpen(&hWaveIn, WAVE_MAPPER, &pFormat, 0, 0, WAVE_FORMAT_DIRECT);

if(result)
{
    char fault[256];
    waveInGetErrorTextA(result, fault, 256);
    MessageBoxA(NULL, fault, "Failed to open waveform input device.", MB_OK | MB_ICONEXCLAMATION);
}

WaveInHdr.lpData = (LPSTR)waveIn;
WaveInHdr.dwBufferLength = 2 * NUMPTS;
WaveInHdr.dwBytesRecorded = 0;
WaveInHdr.dwUser = 0;
WaveInHdr.dwFlags = 0;
WaveInHdr.dwLoops = 0;
waveInPrepareHeader(hWaveIn, &WaveInHdr, sizeof(WAVEHDR));

result = waveInAddBuffer(hWaveIn, &WaveInHdr, sizeof(WAVEHDR));
if(result)
{
    MessageBoxA(NULL, "Failed to read block from device", NULL, MB_OK | MB_ICONEXCLAMATION);
}

result = waveInStart(hWaveIn);
if(result)
{
    MessageBoxA(NULL, "Failed to start recording", NULL, MB_OK | MB_ICONEXCLAMATION);
}

cout << "Recording..." << endl;
Sleep(seconds * 1000); //Sleep while recording

return WaveInHdr;

}

void PlayRecord(WAVEHDR WaveInHdr, int seconds)
{
WAVEFORMATEX pFormat;
pFormat.wFormatTag = WAVE_FORMAT_PCM;
pFormat.nChannels = 1;
pFormat.nSamplesPerSec = 44100;
pFormat.nAvgBytesPerSec = 2 * 44100;
pFormat.nBlockAlign = 2;
pFormat.wBitsPerSample = 16;
pFormat.cbSize = 0;

HWAVEOUT hWaveOut;

if(waveOutOpen(&hWaveOut, WAVE_MAPPER, &pFormat, 0, 0, WAVE_FORMAT_DIRECT))
{
    MessageBoxA(NULL, "Failed to replay", NULL, MB_OK | MB_ICONEXCLAMATION );
}

waveOutWrite(hWaveOut, &WaveInHdr, sizeof(WaveInHdr)); // Playing the data
Sleep(seconds * 1000); //Sleep for as long as there was recorded
 }

int main()
{
PlayRecord(StartRecord(3), 3);
return 0;
}

代码有什么问题?为什么它不起作用?我似乎听不到任何声音......

此外,是否有记录麦克风而不是X秒的选项来记录它,例如直到没有来自麦克风的输入(例如 - 开始录制它,我在麦克风中说一个字,当一两秒钟的沉默停止录音或其他东西?)

谢谢!

1 个答案:

答案 0 :(得分:1)

Re:录制直到麦克风没有输入。是的,准备几个缓冲区并在WaveInStart之前为每个缓冲区调用waveInAddBuffer。 WaveIn将连续并顺序填充缓冲区,并在填充时将它们返回给您。您需要使用WaveIn提供的其中一个通知来了解缓冲区何时被填充。检查缓冲区数据以决定何时停止。如果你想继续前进,那么将每个填充的缓冲区返回给WaveIn,只要你愿意,它就会一直填充它们。