我发现你必须通过 COM 和 CoCreateInstance()。就像是
#include <windows.h>
#include <stdio.h>
#include <XAudio2.h>
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int ncmdshow) {
WAVEFORMATEX format;
format.wFormatTag = 1;
format.nChannels = 1;
format.nSamplesPerSec = 44100;
format.nAvgBytesPerSec = 44100;
format.nBlockAlign = 1;
format.wBitsPerSample = 8;
format.cbSize = 0;
CoInitializeEx(NULL, COINIT_MULTITHREADED);
IXAudio2* pXAudio2 = NULL;
IXAudio2SourceVoice* source = NULL;
IXAudio2MasteringVoice* master = NULL;
HRESULT hr;
if ( FAILED(hr = XAudio2Create( &pXAudio2, 0, XAUDIO2_DEFAULT_PROCESSOR ) ) ) {
MessageBox(0, L"hi", L"hi", 0);
}
if ( FAILED(hr = pXAudio2->CreateMasteringVoice(&master ) ) ) {
MessageBox(0, L"hi", L"hi", 0);
}
if ( FAILED(hr = pXAudio2->CreateSourceVoice(&source, &format) ) ) {
MessageBox(0, L"hi", L"hi", 0);
}
char str[30];
float freq = 0.0;
source->GetFrequencyRatio(&freq);
sprintf(str, "%f", freq);
MessageBoxA(0, str, str, 0);
UINT32 OperationSetCounter = 0;
UINT32 OperationID = UINT32(InterlockedIncrement(LPLONG(&OperationSetCounter)));
if ( FAILED(hr = source->SetFrequencyRatio(1.1,OperationID ) ) ) {
MessageBox(0, L"hi", L"hi", 0);
}
if ( FAILED(hr = pXAudio2->CommitChanges(OperationID ) ) ) {
MessageBox(0, L"hi", L"hi", 0);
}
float freq2 = 0.0;
source->GetFrequencyRatio(&freq2);
sprintf(str, "%f", freq2);
MessageBoxA(0, str, str, 0);
Sleep(2000);
float freq3 = 0.0;
source->GetFrequencyRatio(&freq3);
sprintf(str, "%f", freq3);
if (freq3 != 1.0) {
MessageBoxA(0, str, str, 0);
}
source->Start(0);
return 0;
}