首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在XAudio2上同时播放多个声音?

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

Stack Overflow用户
提问于 2018-03-14 22:13:31
回答 2查看 1.1K关注 0票数 1

我目前正在尝试用XAudio2在Windows中制作一个游戏应用,但我不知道如何让应用在播放声音时不会被阻塞。我尝试在this repository.的示例中调用一个新线程

但这只会导致错误。我尝试在函数中传递一个对主控声音的引用,但它只是引发了一个"XAudio2:必须首先创建一个主控声音“错误。我是不是遗漏了什么?我只是想让它同时播放两个声音,并从那里构建。我看了一下文档,但它非常模糊。

EN

回答 2

Stack Overflow用户

发布于 2018-03-15 13:27:38

XAudio2是一个非阻塞的API。要同时播放两个声音,您至少需要两个“源声音”和一个“掌握声音”。

代码语言:javascript
复制
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 );
);

您应该看看GitHubDirectX Tool Kit for Audio上的示例

如果你想确保两个源声音同时开始,你可以使用:

代码语言:javascript
复制
DX::ThrowIfFailed(
    pSourceVoice1->Start( 0, 1 );
);

DX::ThrowIfFailed(
    pSourceVoice2->Start( 0, 1 );
);

DX::ThrowIfFailed(
    pSourceVoice2->CommitChanges( 1 );
);
票数 2
EN

Stack Overflow用户

发布于 2020-10-23 20:01:55

如果您想同时播放多个声音,可以使用playSound函数并启动各种线程来播放不同的声音,每个声音都是特定的源声音。

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

代码语言:javascript
复制
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 );
    }
}

例如,同时播放两个声音:

代码语言:javascript
复制
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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49279982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档