[C++] 使用XAudio2播放音频
本帖最后由 mzflz 于 2014-10-4 10:38 编辑XAudio2其实也是DirectX的一部分
写了使用XAudio2播放音频的例子,虽然播放的是白噪音
不多说了
上代码:
#include "stdafx.h"
#include <Windows.h>
#include <XAudio2.h>
#include<conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
CoInitializeEx(NULL,COINIT_MULTITHREADED ); //初始化COM库
IXAudio2 * paudio = NULL; //IXAduio2接口
IXAudio2MasteringVoice * pmaster = NULL; //管理缓冲区
IXAudio2SourceVoice * pSource = NULL; //次缓冲区
WAVEFORMATEX format;
XAUDIO2_BUFFER sBuffer; //次缓冲
BYTE * pVBuffer = new BYTE;
XAUDIO2_VOICE_STATE pState = {0};//
for(int i =0 ;i<1024;i++)
{
pVBuffer = rand()%255;
}
ZeroMemory(&format,sizeof(WAVEFORMATEX)); //
format.nChannels = 2 ;//声道数
format.nSamplesPerSec = 11025; //位深
format.wFormatTag= WAVE_FORMAT_PCM ;//PCM标志
//format.nAvgBytesPerSec = ; // 频率
format.wBitsPerSample = 16; //位深
format.nAvgBytesPerSec = (format.wBitsPerSample * format.nSamplesPerSec*format.nChannels)/8;
format.nBlockAlign = (format.nSamplesPerSec/8)*2; //数据块大小
ZeroMemory(&sBuffer,sizeof(XAUDIO2_BUFFER));
sBuffer.Flags = 0;//流缓冲
sBuffer.AudioBytes = 1024;
sBuffer.pAudioData = pVBuffer;
if(XAudio2Create(&paudio)!=S_OK)
{
printf("0");
return 0;
}
if( paudio->CreateMasteringVoice(&pmaster)!=S_OK)
{
printf("2");
return 0;
}
if(paudio->CreateSourceVoice(&pSource,(WAVEFORMATEX *)&format)!=S_OK)
{
printf("3");
return 0;
}
if(pSource->SubmitSourceBuffer(&sBuffer)!=S_OK)
printf("4");
pSource->Start();
while(1)
{
pSource->GetState(&pState);
printf("\n\n\n%d\n\n",pState.BuffersQueued);
if(pState.BuffersQueued==0)
{
for(int i = 0;i<1024;i++)
{
pVBuffer = rand()%255; //填充白噪音
}
if(pSource->SubmitSourceBuffer(&sBuffer)!=S_OK)
printf("4");
}
if(GetAsyncKeyState(VK_ESCAPE))
goto EXIT;
//Sleep(40);
}
EXIT:
pSource->DestroyVoice();
delete [] pVBuffer;
paudio->Release();
return 0;
}
哈哈 。不错不错。
代码很简短。
页:
[1]