Files
mrgameeng/src/MrGameEng.Audio/MusicPlayer.cs
T
Leonid PershinandClaude Fable 5 501d81e19f
CI / build-test (push) Failing after 1m7s
Fix engine-wide code review findings
Collisions: init bucket heads to -1 (QueryAabb hung before the first
rebuild), reset query stamps on truncated QueryAabb (later queries
silently dropped entities), inside-origin raycasts hit at fraction 0 for
circles too, exactly-touching boxes now pair like touching circles.

Graphics: render into the letterbox viewport so the picture matches
ScreenToWorld/WorldToScreen instead of stretching; Y-sort by the
transform pivot rather than the quad center; lock-free snapshot
LayerRegistry (parallel submit read it unsynchronized); validate
InitialCapacity; warn when UseRenderer2D drops options of a later scene.

Core: scenes are explicitly single-use (re-loading threw silently
duplicated systems/entities before — now it throws), Scene.RegisterUnload
for per-scene resources, a switch requested during the reveal phase
covers again instead of hard-swapping, borderless fullscreen
(HardwareModeSwitch off), InputCapture service for input-suppressing
overlays, host disposes the transition renderer and IDisposable services
on shutdown.

Input: game input reads as released while InputCapture is held; mouse
position and wheel freeze so deltas stay zero.

DevConsole: holds InputCapture while open (typing no longer drives the
camera), Revision increments only under the lock, quoted command
arguments, history capped at 256.

UI: scene Desktop skips Myra input processing while the console is open
(clicks no longer fall through), is disposed on scene unload, and Myra
init no longer depends on a process-static flag.

Audio: validate channel count/sample rate before stopping the previous
track, empty looped oggs no longer hang FillBuffers, the instance stops
when a non-looping track drains (IsPlaying was stuck true).

Atlases: metadata v2 stores per-source size+mtime snapshots, so
timestamp-preserving copies and renames invalidate correctly; loader
checks the version and disposes pages on partial load failure; shared
pages never exceed a non-POT MaxPageSize; oversized items pack first
onto exact-size pages instead of splitting an open shared page; the CLI
validates numeric options.

Assets.Generator: file names are escaped in XML docs and string
literals, members no longer collide with the enclosing class (CS0542),
and the Assets root is resolved against build_property.projectdir so
nested "Assets" directories do not shift region paths.

Pathfinding: queries throw when the grid was resized after construction;
generation stamps survive int overflow.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 21:18:08 +03:00

139 lines
4.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Microsoft.Xna.Framework.Audio;
using MrGameEng.Core;
using NVorbis;
namespace MrGameEng.Audio;
/// <summary>
/// Streams ogg music from disk through a <see cref="DynamicSoundEffectInstance"/> using NVorbis.
/// One track plays at a time; samples are decoded on demand in ~0.5 s buffers, so even long
/// tracks use almost no memory.
/// </summary>
public sealed class MusicPlayer : IDisposable
{
private const int BufferedSubmissions = 3;
private VorbisReader? _reader;
private DynamicSoundEffectInstance? _instance;
private float[] _sampleBuffer = [];
private byte[] _byteBuffer = [];
private bool _loop;
private float _volume = 1f;
/// <summary>Volume 0..1 applied to the playing and future tracks.</summary>
public float Volume
{
get => _volume;
set
{
_volume = Math.Clamp(value, 0f, 1f);
if (_instance is not null)
{
_instance.Volume = _volume;
}
}
}
/// <summary>True while a track is playing (not stopped or paused).</summary>
public bool IsPlaying => _instance?.State == SoundState.Playing;
/// <summary>Starts streaming <paramref name="track"/>, stopping the previous one.</summary>
public void Play(MusicTrack track, bool loop = true)
{
// Валидация до Stop(): негодный файл не должен обрывать играющий трек.
var reader = new VorbisReader(track.FullPath);
if (reader.Channels is < 1 or > 2)
{
reader.Dispose();
throw new NotSupportedException(
$"Music '{track.FullPath}' has {reader.Channels} channels; only mono and stereo are supported.");
}
if (reader.SampleRate is < 8000 or > 48000)
{
reader.Dispose();
throw new NotSupportedException(
$"Music '{track.FullPath}' has sample rate {reader.SampleRate} Hz; supported range is 800048000 Hz.");
}
Stop();
_loop = loop;
_reader = reader;
// ~0.5 seconds of samples per submitted buffer.
var samplesPerBuffer = _reader.SampleRate * _reader.Channels / 2;
_sampleBuffer = new float[samplesPerBuffer];
_byteBuffer = new byte[samplesPerBuffer * 2];
_instance = new DynamicSoundEffectInstance(
_reader.SampleRate,
_reader.Channels == 1 ? AudioChannels.Mono : AudioChannels.Stereo)
{
Volume = _volume,
};
_instance.BufferNeeded += (_, _) => FillBuffers();
FillBuffers();
_instance.Play();
}
/// <summary>Pauses the current track.</summary>
public void Pause() => _instance?.Pause();
/// <summary>Resumes a paused track.</summary>
public void Resume() => _instance?.Resume();
/// <summary>Stops playback and releases the decoder.</summary>
public void Stop()
{
_instance?.Dispose();
_instance = null;
_reader?.Dispose();
_reader = null;
}
/// <inheritdoc />
public void Dispose() => Stop();
private void FillBuffers()
{
if (_instance is null || _reader is null)
{
return;
}
while (_instance.PendingBufferCount < BufferedSubmissions)
{
var read = _reader.ReadSamples(_sampleBuffer, 0, _sampleBuffer.Length);
if (read == 0)
{
// SamplePosition > 0 отличает конец трека от пустого файла: после перемотки
// на 0 повторный read == 0 не зацикливается, а завершает воспроизведение.
if (_loop && _reader.SamplePosition > 0)
{
_reader.SamplePosition = 0;
continue;
}
// Конец незацикленного трека (или пустой файл): когда буферы доиграли,
// останавливаем инстанс — иначе IsPlaying остаётся true навсегда.
if (_instance.PendingBufferCount == 0)
{
_instance.Stop();
}
return;
}
for (var i = 0; i < read; i++)
{
var sample = (short)(Math.Clamp(_sampleBuffer[i], -1f, 1f) * short.MaxValue);
_byteBuffer[i * 2] = (byte)sample;
_byteBuffer[i * 2 + 1] = (byte)(sample >> 8);
}
_instance.SubmitBuffer(_byteBuffer, 0, read * 2);
}
}
}