C# 如何使用XAudio2重复播放相同的声音?
我需要在我的应用程序中重复播放单个声音,例如,使用XAudio2播放枪声 这是我为此编写的代码的一部分:C# 如何使用XAudio2重复播放相同的声音?,c#,audio,directx,xaudio2,C#,Audio,Directx,Xaudio2,我需要在我的应用程序中重复播放单个声音,例如,使用XAudio2播放枪声 这是我为此编写的代码的一部分: public sealed class X2SoundPlayer : IDisposable { private readonly WaveStream _stream; private readonly AudioBuffer _buffer; private readonly SourceVoice _voice;
public sealed class X2SoundPlayer : IDisposable
{
private readonly WaveStream _stream;
private readonly AudioBuffer _buffer;
private readonly SourceVoice _voice;
public X2SoundPlayer(XAudio2 device, string pcmFile)
{
var fileStream = File.OpenRead(pcmFile);
_stream = new WaveStream(fileStream);
fileStream.Close();
_buffer = new AudioBuffer
{
AudioData = _stream,
AudioBytes = (int) _stream.Length,
Flags = BufferFlags.EndOfStream
};
_voice = new SourceVoice(device, _stream.Format);
}
public void Play()
{
_voice.SubmitSourceBuffer(_buffer);
_voice.Start();
}
public void Dispose()
{
_stream.Close();
_stream.Dispose();
_buffer.Dispose();
_voice.Dispose();
}
}
上面的代码实际上是基于SlimDX示例的
它现在的作用是,当我反复调用Play()时,声音会像这样播放:
声音->声音->声音
所以它只是填充缓冲区并播放它
但是,我需要能够在播放当前声音时播放相同的声音,因此这两种或更多种声音应该有效地同时混合播放
这里有什么我错过的,或者我目前的解决方案不可能做到的(也许SubmixVoices可以帮助)
我试图在文档中找到一些相关的东西,但没有成功,而且网上也没有多少例子可以参考
谢谢。尽管出于这个目的使用XACT是更好的选择,因为它支持声音提示(这正是我所需要的),但我还是设法让它以这种方式工作 我已经更改了代码,所以它总是从流中创建新的SourceVoice对象并播放它
// ------ code piece
/// <summary>
/// Gets the available voice.
/// </summary>
/// <returns>New SourceVoice object is always returned. </returns>
private SourceVoice GetAvailableVoice()
{
return new SourceVoice(_player.GetDevice(), _stream.Format);
}
/// <summary>
/// Plays this sound asynchronously.
/// </summary>
public void Play()
{
// get the next available voice
var voice = GetAvailableVoice();
if (voice != null)
{
// submit new buffer and start playing.
voice.FlushSourceBuffers();
voice.SubmitSourceBuffer(_buffer);
voice.Start();
}
}
/----代码段
///
///获取可用的语音。
///
///始终返回新的SourceVoice对象。
私有源语音GetAvailableVoice()
{
返回新的SourceVoice(_player.GetDevice(),_stream.Format);
}
///
///异步播放此声音。
///
公共游戏
{
//获取下一个可用语音
var voice=GetAvailableVoice();
如果(语音!=null)
{
//提交新缓冲区并开始播放。
voice.FlushSourceBuffers();
voice.SubmitSourceBuffer(_buffer);
voice.Start();
}
}