public SourceVoice Play(EffectSound sound)
{
var waveFormat = sound.Stream.Format;
List<SourceVoice> voices;
lock (instances)
{
if (!instances.TryGetValue(waveFormat, out voices))
{
voices = new List<SourceVoice>();
instances.Add(waveFormat, voices);
}
// Clean non-playing source
var voiceToDelete = new List<SourceVoice>();
foreach (var voice in voices)
{
if (voice.State.BuffersQueued == 0)
voiceToDelete.Add(voice);
}
voiceToDelete.ForEach(x =>
{
voices.Remove(x);
x.Stop();
x.DestroyVoice();
x.Dispose();
});
if (voices.Count >= this.maxInstances)
// Too many instances
return null;
var newVoice = new SourceVoice(this.xaudio2, waveFormat, true);
newVoice.BufferEnd += newVoice_BufferEnd;
voices.Add(newVoice);
newVoice.SubmitSourceBuffer(sound.Buffer, sound.Stream.DecodedPacketsInfo);
newVoice.Start();
return newVoice;
}
}