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
NAudioPlaybackHandle.cs
1using Microsoft.Extensions.Logging;
2using NAudio.Wave;
3using NAudio.Wave.SampleProviders;
4
6
11internal sealed class NAudioPlaybackHandle : IAudioPlaybackHandle
12{
13 private readonly string _key;
14 private readonly object _controlLock = new();
15 private readonly WaveStream _waveStream;
16 private readonly IWavePlayer _outputDevice;
17 private readonly VariableSpeedSampleProvider _speedProvider;
18
19 private PanningSampleProvider? _monoPanProvider;
20 private StereoPanSampleProvider? _stereoPanProvider;
21 private VolumeSampleProvider? _volumeProvider;
22
23 private bool _stopRequested;
24 private bool? _pendingPlay;
25 private TimeSpan? _pendingPosition;
26 private bool _disposed;
27 private bool _isLooping;
28 private float _volume;
29 private float _pan;
30 private float _playbackSpeed;
31
42 public NAudioPlaybackHandle(
43 string key,
44 WaveStream waveStream,
45 string? temporaryFilePath,
46 float volume,
47 float pan,
48 float playbackSpeed,
49 IWavePlayer? outputDevice = null)
50 {
51 _key = key;
52 _waveStream = waveStream;
53 TemporaryFilePath = temporaryFilePath;
54 _volume = Math.Clamp(volume, 0f, 1f);
55 _pan = Math.Clamp(pan, -1f, 1f);
56
57 _playbackSpeed = Math.Clamp(
58 playbackSpeed,
59 AudioResource.MinimumPlaybackSpeed,
60 AudioResource.MaximumPlaybackSpeed);
61
62 var source = _waveStream.ToSampleProvider();
63
64 _speedProvider = new VariableSpeedSampleProvider(source)
65 {
66 PlaybackSpeed = _playbackSpeed
67 };
68
69 _outputDevice = outputDevice ?? new WaveOutEvent();
70
71 try
72 {
73 _outputDevice.Init(BuildAudioGraph(_speedProvider));
74 }
75 catch
76 {
77 _outputDevice.Dispose();
78 throw;
79 }
80
81 _outputDevice.PlaybackStopped += OnPlaybackStopped;
82 }
83
87 public event EventHandler? PlaybackCompleted;
88
93 public AudioPlaybackState State => _outputDevice.PlaybackState switch
94 {
95 PlaybackState.Playing => AudioPlaybackState.Playing,
96 PlaybackState.Paused => AudioPlaybackState.Paused,
97 _ => AudioPlaybackState.Stopped
98 };
99
104 public TimeSpan CurrentTime
105 {
106 get
107 {
108 lock (_controlLock)
109 return _pendingPosition ?? _waveStream.CurrentTime;
110 }
111 }
112
117 public TimeSpan Duration => _waveStream.TotalTime;
118
122 public string? TemporaryFilePath { get; }
123
127 public bool IsLooping
128 {
129 get => _isLooping;
130 set => _isLooping = value;
131 }
132
137 public float Volume
138 {
139 get => _volume;
140 set
141 {
142 _volume = Math.Clamp(value, 0f, 1f);
143
144 if (_volumeProvider is not null)
145 _volumeProvider.Volume = _volume;
146 }
147 }
148
153 public float Pan
154 {
155 get => _pan;
156 set
157 {
158 _pan = Math.Clamp(value, -1f, 1f);
159
160 if (_monoPanProvider is not null)
161 _monoPanProvider.Pan = _pan;
162 else if (_stereoPanProvider is not null)
163 ApplyStereoPan(_stereoPanProvider, _pan);
164 }
165 }
166
171 public float PlaybackSpeed
172 {
173 get => _playbackSpeed;
174 set
175 {
176 _playbackSpeed = Math.Clamp(value, AudioResource.MinimumPlaybackSpeed, AudioResource.MaximumPlaybackSpeed);
177 _speedProvider.PlaybackSpeed = _playbackSpeed;
178 }
179 }
180
185 public void Play(bool fromStart = true)
186 {
187 lock (_controlLock)
188 {
189 ThrowIfDisposed();
190
191 // WaveOutEvent.Stop completes asynchronously. Restart only after its worker exits.
192 if (_stopRequested)
193 {
194 _pendingPlay = fromStart;
195 return;
196 }
197
198 if (fromStart)
199 {
200 if (State != AudioPlaybackState.Stopped)
201 {
202 _stopRequested = true;
203 _pendingPlay = true;
204 _outputDevice.Stop();
205 return;
206 }
207
208 _speedProvider.Reset(() => _waveStream.Position = 0);
209 }
210
211 _stopRequested = false;
212
213 if (State != AudioPlaybackState.Playing)
214 _outputDevice.Play();
215 }
216 }
217
221 public void Pause()
222 {
223 lock (_controlLock)
224 {
225 ThrowIfDisposed();
226
227 if (State == AudioPlaybackState.Playing)
228 _outputDevice.Pause();
229 }
230 }
231
235 public void Resume()
236 {
237 lock (_controlLock)
238 {
239 ThrowIfDisposed();
240
241 if (State == AudioPlaybackState.Paused)
242 _outputDevice.Play();
243 }
244 }
245
250 public void Seek(TimeSpan position)
251 {
252 lock (_controlLock)
253 {
254 ThrowIfDisposed();
255
256 var clamped = position < TimeSpan.Zero
257 ? TimeSpan.Zero
258 : position > Duration
259 ? Duration
260 : position;
261
262 if (_stopRequested)
263 {
264 _pendingPosition = clamped;
265 return;
266 }
267
268 var wasPlaying = State == AudioPlaybackState.Playing;
269
270 if (wasPlaying)
271 _outputDevice.Pause();
272
273 _speedProvider.Reset(() => _waveStream.CurrentTime = clamped);
274
275 if (wasPlaying)
276 _outputDevice.Play();
277 }
278 }
279
284 public void Stop()
285 {
286 lock (_controlLock)
287 {
288 ThrowIfDisposed();
289 _pendingPlay = null;
290
291 if (_stopRequested)
292 {
293 _pendingPosition = TimeSpan.Zero;
294 return;
295 }
296
297 if (State != AudioPlaybackState.Stopped)
298 {
299 _pendingPosition = TimeSpan.Zero;
300 _stopRequested = true;
301 _outputDevice.Stop();
302 }
303 else
304 _speedProvider.Reset(() => _waveStream.Position = 0);
305 }
306 }
307
308 private ISampleProvider BuildAudioGraph(ISampleProvider source)
309 {
310 ISampleProvider current = source;
311 var channels = current.WaveFormat.Channels;
312
313 switch (channels)
314 {
315 case <= 0:
316 Engine.Logger.LogWarning(
317 "AudioResource {Key} has invalid channel count: {ChannelCount}",
318 _key,
319 channels);
320
321 break;
322
323 case 1:
324 _monoPanProvider = new PanningSampleProvider(current) { Pan = _pan };
325 current = _monoPanProvider;
326 break;
327
328 case 2:
329 _stereoPanProvider = new StereoPanSampleProvider(current);
330 ApplyStereoPan(_stereoPanProvider, _pan);
331 current = _stereoPanProvider;
332 break;
333
334 default:
335 var mux = new MultiplexingSampleProvider(new[] { current }, 2);
336 mux.ConnectInputToOutput(0, 0);
337 mux.ConnectInputToOutput(1, 1);
338 current = mux;
339 _stereoPanProvider = new StereoPanSampleProvider(current);
340 ApplyStereoPan(_stereoPanProvider, _pan);
341 current = _stereoPanProvider;
342 break;
343 }
344
345 _volumeProvider = new VolumeSampleProvider(current) { Volume = _volume };
346 return _volumeProvider;
347 }
348
349 private void OnPlaybackStopped(object? sender, StoppedEventArgs e)
350 {
351 var completed = false;
352
353 lock (_controlLock)
354 {
355 if (_disposed)
356 return;
357
358 if (_pendingPosition is { } position)
359 {
360 _speedProvider.Reset(() => _waveStream.CurrentTime = position);
361 _pendingPosition = null;
362 }
363
364 if (e.Exception is not null)
365 {
366 _stopRequested = false;
367 _pendingPlay = null;
368
369 Engine.Logger.LogError(
370 e.Exception,
371 "NAudio playback stopped due to an error for audio resource {Key}",
372 _key);
373
374 return;
375 }
376
377 if (_stopRequested)
378 {
379 _stopRequested = false;
380 var pendingPlay = _pendingPlay;
381 _pendingPlay = null;
382
383 if (pendingPlay.HasValue)
384 Play(pendingPlay.Value);
385
386 return;
387 }
388
389 var reachedEnd = _waveStream.Position >= _waveStream.Length;
390
391 if (_isLooping && reachedEnd)
392 {
393 Play(true);
394 return;
395 }
396
397 completed = reachedEnd;
398 }
399
400 // User callbacks may unload through the manager; never invoke them under
401 // the device control lock (manager disposal takes these locks in reverse).
402 if (completed)
403 PlaybackCompleted?.Invoke(this, EventArgs.Empty);
404 }
405
406 private static void ApplyStereoPan(StereoPanSampleProvider provider, float pan)
407 {
408 var value = Math.Clamp(pan, -1f, 1f);
409 var angle = (value + 1f) * 0.5f * (float)(Math.PI / 2);
410 provider.LeftVolume = MathF.Cos(angle);
411 provider.RightVolume = MathF.Sin(angle);
412 }
413
414 private void ThrowIfDisposed()
415 {
416 ObjectDisposedException.ThrowIf(_disposed, this);
417 }
418
423 public void Dispose()
424 {
425 lock (_controlLock)
426 {
427 if (_disposed)
428 return;
429
430 _outputDevice.PlaybackStopped -= OnPlaybackStopped;
431
432 try
433 {
434 _stopRequested = true;
435 _outputDevice.Stop();
436 }
437 catch
438 {
439 // Best effort during teardown.
440 }
441
442 _outputDevice.Dispose();
443 _waveStream.Dispose();
444 NAudioReaderRegistry.TryDelete(TemporaryFilePath);
445 _disposed = true;
446 }
447 }
448}
void Resume()
Resume playback after a pause.
void Pause()
Pause playback. Calling Resume should continue from the paused position.
void Stop()
Stop playback and reset the current position to the start.
AudioPlaybackState
Describes the current playback state of an audio resource without exposing backend-specific playback ...