Added more sound effeects. Added audio manager.
This commit is contained in:
37
AlientAttack.MonoGame/Audio/SoundPool.cs
Normal file
37
AlientAttack.MonoGame/Audio/SoundPool.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user