Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
WaveProviderToWaveStream.cs
1using NAudio.Wave;
2
3namespace Gondwana.Audio.Midi;
4
8public class WaveProviderToWaveStream : WaveStream
9{
10 private readonly object _gate = new();
11 private readonly IWaveProvider source;
12 private readonly WaveFormat waveFormat;
13 private long position;
14 private readonly long _midiLengthBytes;
15
16 // Delegate for seeking into the underlying synthesizer
17 private readonly Action<TimeSpan>? _seekHandler;
18
25 public WaveProviderToWaveStream(IWaveProvider source, double durationSeconds, Action<TimeSpan>? seekHandler)
26 {
27 ArgumentNullException.ThrowIfNull(source);
28
29 if (!double.IsFinite(durationSeconds) || durationSeconds < 0)
30 throw new ArgumentOutOfRangeException(nameof(durationSeconds));
31
32 this.source = source;
33 this.waveFormat = source.WaveFormat;
34 _midiLengthBytes = checked((long)(durationSeconds * waveFormat.SampleRate) * waveFormat.BlockAlign);
35 _seekHandler = seekHandler;
36 }
37
41 public override WaveFormat WaveFormat => waveFormat;
42
46 public override long Length => _midiLengthBytes;
47
52 public override long Position
53 {
54 get
55 {
56 lock (_gate)
57 return position;
58 }
59 set
60 {
61 lock (_gate)
62 {
63 if (_seekHandler == null)
64 throw new NotSupportedException("Seeking is not supported for this stream.");
65
66 var clamped = Math.Clamp(value, 0, Length);
67 clamped -= clamped % waveFormat.BlockAlign;
68 var seconds = (double)clamped / waveFormat.AverageBytesPerSecond;
69 _seekHandler(TimeSpan.FromSeconds(seconds));
70 position = clamped;
71 }
72 }
73 }
74
82 public override int Read(byte[] buffer, int offset, int count)
83 {
84 ArgumentNullException.ThrowIfNull(buffer);
85 _ = buffer.AsSpan(offset, count);
86
87 lock (_gate)
88 {
89 int remaining = (int)Math.Min(count, Length - position);
90 remaining -= remaining % waveFormat.BlockAlign;
91
92 if (remaining == 0)
93 return 0;
94
95 int read = source.Read(buffer, offset, remaining);
96 position += read;
97 return read;
98 }
99 }
100}
WaveProviderToWaveStream(IWaveProvider source, double durationSeconds, Action< TimeSpan >? seekHandler)
Initializes a new instance of the WaveProviderToWaveStream class.
override long Position
Gets or sets the current position in the stream in bytes.
override WaveFormat WaveFormat
Gets the wave format of the stream.
override long Length
Gets the length of the stream in bytes.
override int Read(byte[] buffer, int offset, int count)
Reads audio data from the underlying wave provider.