1

在互联网的帮助下,我编写了一个程序,它在运行时一直从麦克风捕获音频。一切都很好,但我需要减少 CPU 的费用,因为现在它大约是 30-35%。

int SoundCapture()
{
const int NUMPTS = 8000 * 1; // Sample rate * seconds
int sampleRate = 8000;
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
    HWAVEIN hWaveIn;
    WAVEFORMATEX waveform;
    WAVEHDR waveHeader;

waveform.wFormatTag = WAVE_FORMAT_PCM;  // simple, uncompressed format
waveform.nChannels = 1;                 //  1=mono, 2=stereo
waveform.nSamplesPerSec = 8000;
waveform.nAvgBytesPerSec = 8000;        // = nSamplesPerSec * n.Channels * wBitsPerSample/8
waveform.nBlockAlign = 1;               // = n.Channels * wBitsPerSample/8
waveform.wBitsPerSample = 8;            //  16 for high quality, 8 for telephone-grade
waveform.cbSize = 0;
MMRESULT result = waveInOpen(&hWaveIn, WAVE_MAPPER, &waveform, 0, 0, WAVE_FORMAT_DIRECT);
if (result)
{
    std::cout << "Something wrong with WaveOpen";
    std::cin.ignore(2);
    return 0;
}
// Set up and prepare header for input
waveHeader.lpData = (LPSTR)waveIn; //pointer to waveform buffer
waveHeader.dwBufferLength = NUMPTS;
waveHeader.dwBytesRecorded = 0;
waveHeader.dwUser = 0L;
waveHeader.dwFlags = 0L;
waveHeader.dwLoops = 0L;
waveInPrepareHeader(hWaveIn, &waveHeader, sizeof(WAVEHDR));

// Insert a wave input buffer
result = waveInAddBuffer(hWaveIn, &waveHeader, sizeof(WAVEHDR));
if (result)
{
    std::cout << "Something wrong with waveInAddBuffer";
    std::cin.ignore(2);
    return 0;
}
// Commence sampling input
time_t t = time(0);   // get time now
result = waveInStart(hWaveIn);
if (result)
{
    std::cout << "Something wrong with WaveStart";
    std::cin.ignore(2);
    return 0;
}


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

这是产生电荷的全部功能。我怎样才能减少它?或者我不能?使用 WindowsAPI 以外的其他捕获方法?

我试图减少每秒的样本,但这并没有太大帮助。我想这与缓冲区有关,但需要任何提示。

干杯

4

1 回答 1

0

正如我们所评论的,cpu 消耗是由于在 do-while 循环中的主动等待。我建议在 windows 中使用 Event 对象。但作为直接的解决方案,我建议睡几毫秒(进行相关计算以确切知道什么是完美时间,正如@MSalters 在他的评论中所说的那样)。

基于How do you make a program sleep in C++ on Win 32? 一个可能的解决方案是:

#include <windows.h>

//....
do {
   Sleep(X);
} 
while (waveInUnprepareHeader(hWaveIn, &waveHeader, sizeof(WAVEHDR)) == WAVERR_STILLPLAYING);
//....
于 2018-07-12T13:15:59.050 回答