using Microsoft.Xna.Framework.Audio; using System; namespace AlienAttack.MonoGame.Audio; public sealed class SoundPool { private readonly SoundEffectInstance[] _voices; private int _cursor; public SoundPool(SoundEffect effect, int maxVoices) { ArgumentOutOfRangeException.ThrowIfLessThan(maxVoices, 1); _voices = new SoundEffectInstance[maxVoices]; for (int i = 0; i < maxVoices; i++) _voices[i] = effect.CreateInstance(); } public void Play(float volume = 1f, float pitch = 0f, float pan = 0f) { SoundEffectInstance instance = _voices[_cursor]; _cursor = (_cursor + 1) % _voices.Length; // "Voice stealing": stop if currently playing, then reuse immediately if (instance.State == SoundState.Playing) instance.Stop(); instance.Volume = Math.Clamp(volume, 0f, 1f); instance.Pitch = Math.Clamp(pitch, -1f, 1f); instance.Pan = Math.Clamp(pan, -1f, 1f); instance.Play(); } }