PortAudio 采用回调方式,这样可以一帧一帧的处理
头文件:
#ifndef __CAPTURE_AUDIO__
#define __CAPTURE_AUDIO__
#include <functional>
#include <windows.h>
#include "portaudio.h"
#define SAMPLE_RATE 44100
class CaptureAudio
{
public:
CaptureAudio();
~CaptureAudio();
public:
bool Init(const std::function<void(unsigned char* pPcmAudioData, long nLen)>& pFunc);
void Uninit();
private:
static int Audio_Pcm_CB(const void* input, void* output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData);
private:
static int m_nExiting;
private:
PaStream* m_pAudioStream = nullptr;
private:
static std::function<void(unsigned char* pPcmAudioData, long nLen)> m_pFunc;
};
#endif
源文件:
#include "CaptureAudio.h"
#include <chrono>
#include <thread>
#include <direct.h>
using namespace std;
int CaptureAudio::m_nExiting = 0;
std::function<void(unsigned char* pPcmAudioData, long nLen)> CaptureAudio::m_pFunc = nullptr;
CaptureAudio::CaptureAudio()
{
}
CaptureAudio::~CaptureAudio()
{
}
int CaptureAudio::Audio_Pcm_CB(const void* input, void* output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData)
{
if (m_pFunc) {
m_pFunc((unsigned char*)input, frameCount * 1 /*输入通道*/ * sizeof(short) /*16位bit, paInt16*/);
}
if (m_nExiting){
return paComplete;
}
else {
return paContinue;
}
}
bool CaptureAudio::Init(const std::function<void(unsigned char* pPcmAudioData, long nLen)>& pFunc)
{
PaError nErr = Pa_Initialize();
if (nErr != paNoError) {
return false;
}
PaStreamParameters inputParameters;
inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
if (inputParameters.device == paNoDevice) {
return false;
}
inputParameters.channelCount = 1;
inputParameters.sampleFormat = paInt16;
inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
inputParameters.hostApiSpecificStreamInfo = NULL;
nErr = Pa_OpenStream(
&m_pAudioStream,
&inputParameters,
NULL, /* &outputParameters, */
SAMPLE_RATE,
SAMPLE_RATE / 1000 * 200,
paClipOff, /* we won't output out of range samples so don't bother clipping them */
Audio_Pcm_CB, /* no callback, use blocking API */
NULL); /* no callback, so no callback userData */
if (nErr != paNoError) {
return false;
}
//启动录音
Pa_StartStream(m_pAudioStream);
//
m_pFunc = pFunc;
return true;
}
void CaptureAudio::Uninit()
{
m_nExiting = 1;
Pa_CloseStream(m_pAudioStream);
Pa_Terminate();
}
打开录制的pcm