如何在XAudio2上同时播放多个声音?

时间:2018-03-14 14:13:31

标签: c++ windows xaudio2

我目前正在尝试使用XAudio2在Windows中制作游戏应用程序,我无法弄清楚如何在播放声音时使应用程序不被阻止。我尝试在this repository.

中的示例中调用一个新线程

但它只会导致错误。我尝试在函数中传递对母版语音的引用,但之后它只是引发了“XAudio2:必须首先创建母带语音”错误。我错过了什么吗?我只是想让它同时播放两个声音并从那里开始构建。我查了一下文档,但它很模糊。

2 个答案:

答案 0 :(得分:0)

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 );
);

答案 1 :(得分:0)

如果您想同时播放多种声音,请使用at功能,并启动各种线程来播放特定声音中的每种声音。

XAudio2将负责将每个声音映射到可用声道(或者,如果您有更高级的系统,则可以使用playSound自己指定映射)。

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 );
    }
}