Files
mrgameeng/src/MrGameEng.Audio/AudioManager.cs
T
Leonid Pershin ef1111bcb6
CI / build-test (push) Successful in 1m10s
Enhance audio management and documentation
Added a MasterVolume property to the AudioManager for unified control over sound effects and music volume. Updated the Play method to incorporate MasterVolume adjustments. Enhanced documentation in CLAUDE.md and architecture.md to reflect changes in audio management and overall engine architecture. Introduced a new test project for audio functionalities in the solution file.
2026-06-12 08:41:39 +03:00

63 lines
2.2 KiB
C#

using Microsoft.Xna.Framework.Audio;
using MrGameEng.Core;
namespace MrGameEng.Audio;
/// <summary>
/// Sound-effect playback with a module-level volume, plus the <see cref="Music"/> player.
/// Registered as a service via <c>context.UseAudio()</c>.
/// </summary>
public sealed class AudioManager : IDisposable
{
/// <summary>The streaming music player.</summary>
public MusicPlayer Music { get; } = new();
/// <summary>Volume multiplier applied to every sound effect, 0..1.</summary>
public float SoundVolume
{
get => _soundVolume;
set => _soundVolume = Math.Clamp(value, 0f, 1f);
}
/// <summary>
/// Master volume 0..1 applied on top of <see cref="SoundVolume"/> for sound effects and
/// mirrored onto <see cref="MusicPlayer.Volume"/>, so a single knob (e.g. a settings
/// slider) controls both effects and music.
/// </summary>
public float MasterVolume
{
get => _masterVolume;
set
{
_masterVolume = Math.Clamp(value, 0f, 1f);
Music.Volume = _masterVolume;
}
}
private float _soundVolume = 1f;
private float _masterVolume = 1f;
/// <summary>Plays a sound effect (fire and forget).</summary>
/// <param name="sound">The loaded sound effect.</param>
/// <param name="volume">Per-play volume 0..1, multiplied with <see cref="SoundVolume"/>.</param>
/// <param name="pitch">Pitch offset in octaves, -1..1.</param>
/// <param name="pan">Stereo pan, -1 (left) .. 1 (right).</param>
public void Play(SoundEffect sound, float volume = 1f, float pitch = 0f, float pan = 0f) =>
sound.Play(Math.Clamp(volume, 0f, 1f) * _soundVolume * _masterVolume, pitch, pan);
/// <inheritdoc />
public void Dispose() => Music.Dispose();
}
/// <summary>Wires the audio module into the engine.</summary>
public static class AudioEngineExtensions
{
/// <summary>Creates the <see cref="AudioManager"/> and registers it as a service. Call once at startup.</summary>
public static AudioManager UseAudio(this EngineContext context)
{
var manager = new AudioManager();
context.Services.Add(manager);
return manager;
}
}