资源简介
利用C++实现音频录音功能,定义音频头的数据格式,通道数为2,通道字节数16为录的声音更为清晰,无杂音。
代码片段和文件信息
#include “SoundRecord.h“
#include
CSoundRecord::CSoundRecord(void):m_bPlay(false)
m_Time(0)
m_hOPFile(nullptr)
{
m_hWaveIn=NULL;
ZeroMemory(&m_stWFEXsizeof(WAVEFORMATEX));
ZeroMemory(m_stWHDRMAX_BUFFERS*sizeof(WAVEHDR));
}
CSoundRecord::~CSoundRecord(void)
{
}
bool CSoundRecord::initDevice()
{
MMRESULT mRes=0;
int nT1=0;
//填充数据头结构体
m_stWFEX.nSamplesPerSec = m_samplefreq;
m_stWFEX.nAvgBytesPerSec = m_samplefreq * m_channels * m_channelbits / 8;//每秒所需字节数
m_stWFEX.nBlockAlign = m_channels * m_channelbits / 8;//一个采样的字节数
m_stWFEX.nChannels = m_channels; //1为单通道,2为双通道
m_stWFEX.wFormatTag = 0x0001;//编码方式
m_stWFEX.wBitsPerSample = m_channelbits;//16位,即设置PCM的方式为16位立体声(双通道)
m_stWFEX.cbSize = sizeof(WAVEFORMATEX);
mRes=waveInOpen(&m_hWaveInWAVE_MAPPER&m_stWFEX(DWORD_PTR)waveInProc(DWORD_PTR)thisCALLBACK_FUNCTION);
if(mRes!=MMSYSERR_NOERROR)
{
std::cout << “打开音频设备失败....“ << std::endl;
return false;
}
//新建存储文件
//设置保存的音频文件名称
SYSTEMTIME sysTime;
GetLocalTime( &sysTime );
char fileName[512];
memset(fileName0512);
sprintf_s(fileName“%d_%d_%d_%d_%d_%d.wav“sysTime.wYearsysTime.wMonthsysTime.wDaysysTime.wHoursysTime.wMinutesysTime.wSecond);
ZeroMemory(&m_stmmIFsizeof(MMIOINFO));
//转换 stringTolpwstr
m_FileName = fileName;
std::wstring widstr;
widstr = std::wstring(m_FileName.begin() m_FileName.end());
LPWSTR ff = (LPWSTR)widstr.c_str();
m_hOPFile=mmioOpen(ff&m_stmmIFMMIO_WRITE | MMIO_CREATE);
if(m_hOPFile==NULL)
{
std::cout << “创建文件失败...“ << std::endl;
return false;
}
ZeroMemory(&m_stckOutRIFFsizeof(MMCKINFO));
m_stckOutRIFF.fccType = mmioFOURCC(‘W‘ ‘A‘ ‘V‘ ‘E‘);
mRes=mmioCreateChunk(m_hOPFile &m_stckOutRIFF MMIO_CREATERIFF);
if(mRes!=MMSYSERR_NOERROR)
{
std::cout << “创建RIFF-WAVE数据块失败“ << std::endl;
}
ZeroMemory(&m_stckOutsizeof(MMCKINFO));
m_stckOut.ckid = mmioFOURCC(‘f‘ ‘m‘ ‘t‘ ‘ ‘);
m_stckOut.cksize = sizeof(m_stWFEX);
mRes=mmioCreateChunk(m_hOPFile &m_stckOut 0);
if(mRes!=MMSYSERR_NOERROR)
{
std::cout << “创建fmt数据块失败“ << std::endl;
}
nT1=mmioWrite(m_hOPFile (HPSTR) &m_stWFEX sizeof(m_stWFEX));
if(nT1!=sizeof(m_stWFEX))
{
std::cout << “写音频数据格式失败“ << std::endl;
}
mRes=mmioAscend(m_hOPFile &m_stckOut 0);
if(mRes!=MMSYSERR_NOERROR)
{
std::cout << “升序排列数据“ << std::endl;
}
m_stckOut.ckid = mmioFOURCC(‘d‘ ‘a‘ ‘t‘ ‘a‘);
mRes=mmioCreateChunk(m_hOPFile &m_stckOut 0);
if(mRes!=MMSYSERR_NOERROR)
{
std::cout << “创建data数据块失败“ << std::endl;
}
}
void CSoundRecord::closeDevice()
{
MMRESULT mRes=0;
if(m_hWaveIn)
{
unPrepareBuffers();
mRes=waveInClose(m_hWaveIn);
}
if(m_hOPFile)
{
mRes=mmioAscend(m_hOPFile &m_stckOut 0);
if(mRes!=MMSYSERR_NOERROR)
{
std::cout << “重定向音频头数据失败“ << std::endl;
return ;
}
mRes=mmioAscend(m_hOPFile &m_stckOutRIFF 0);
if(mRes!=MMSY
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 6499 2018-08-30 15:49 sound\SoundRecord.cpp
文件 1011 2018-08-30 15:51 sound\SoundRecord.h
目录 0 2018-08-30 15:53 sound
----------- --------- ---------- ----- ----
7510 3
评论
共有 条评论