我目前正在尝试用XAudio2在Windows中制作一个游戏应用,但我不知道如何让应用在播放声音时不会被阻塞。我尝试在this repository.的示例中调用一个新线程
但这只会导致错误。我尝试在函数中传递一个对主控声音的引用,但它只是引发了一个"XAudio2:必须首先创建一个主控声音“错误。我是不是遗漏了什么?我只是想让它同时播放两个声音,并从那里构建。我看了一下文档,但它非常模糊。
发布于 2018-03-15 13:27:38
XAudio2是一个非阻塞的API。要同时播放两个声音,您至少需要两个“源声音”和一个“掌握声音”。
DX::ThrowIfFailed(
CoInitializeEx( nullptr, COINIT_MULTITHREADED )
);
Microsoft::WRL::ComPtr<IXAudio2> pXAudio2;
// Note that only IXAudio2 (and APOs) are COM reference counted
DX::ThrowIfFailed(
XAudio2Create( pXAudio2.GetAddressOf(), 0 )
);
IXAudio2MasteringVoice* pMasteringVoice = nullptr;
DX::ThrowIfFailed(
pXAudio2->CreateMasteringVoice( &pMasteringVoice )
);
IXAudio2SourceVoice* pSourceVoice1 = nullptr;
DX::ThrowIfFailed(
pXaudio2->CreateSourceVoice( &pSourceVoice1, &wfx ) )
// The default 'pSendList' will be just to the pMasteringVoice
);
IXAudio2SourceVoice* pSourceVoice2 = nullptr;
DX::ThrowIfFailed(
pXaudio2->CreateSourceVoice( &pSourceVoice2, &wfx) )
// Doesn't have to be same format as other source voice
// And doesn't have to match the mastering voice either
);
DX::ThrowIfFailed(
pSourceVoice1->SubmitSourceBuffer( &buffer )
);
DX::ThrowIfFailed(
pSourceVoice2->SubmitSourceBuffer( &buffer /* could be different WAV data or not */)
);
DX::ThrowIfFailed(
pSourceVoice1->Start( 0 );
);
DX::ThrowIfFailed(
pSourceVoice2->Start( 0 );
);您应该看看GitHub和DirectX Tool Kit for Audio上的示例
如果你想确保两个源声音同时开始,你可以使用:
DX::ThrowIfFailed(
pSourceVoice1->Start( 0, 1 );
);
DX::ThrowIfFailed(
pSourceVoice2->Start( 0, 1 );
);
DX::ThrowIfFailed(
pSourceVoice2->CommitChanges( 1 );
);发布于 2020-10-23 20:01:55
如果您想同时播放多个声音,可以使用playSound函数并启动各种线程来播放不同的声音,每个声音都是特定的源声音。
XAudio2将负责将每个声音映射到可用的通道(或者,如果您有更高级的系统,您可以使用IXAudio2Voice::SetOutputMatrix自己指定映射)。
void playSound( IXAudio2SourceVoice* sourceVoice )
{
BOOL isPlayingSound = TRUE;
XAUDIO2_VOICE_STATE soundState = {0};
HRESULT hres = sourceVoice->Start( 0u );
while ( SUCCEEDED( hres ) && isPlayingSound )
{// loop till sound completion
sourceVoice->GetState( &soundState );
isPlayingSound = ( soundState.BuffersQueued > 0 ) != 0;
Sleep( 100 );
}
}例如,同时播放两个声音:
IXAudio2SourceVoice* pSourceVoice1 = nullptr;
IXAudio2SourceVoice* pSourceVoice2 = nullptr;
// setup the source voices, load the sounds etc..
std::thread thr1{ playSound, pSourceVoice1 };
std::thread thr2{ playSound, pSourceVoice2 };
thr1.join();
thr2.join();https://stackoverflow.com/questions/49279982
复制相似问题