Files
Neutron/src/GamePort/Audio/SdlAudio.cs
T

74 lines
3.0 KiB
C#

using GamePort.Platform;
namespace GamePort.Audio;
/// <summary>Plays recovered WAV unchanged through an SDL3 conversion/mixing stream.</summary>
public sealed class SdlAudio : IDisposable
{
private nint stream;
private nint data;
private int length;
private readonly bool loop;
private bool audioInitialized;
public int SourceFrequency {get;private set;}
public bool Paused { get; private set; }
public bool Muted { get; private set; }
public int QueuedBytes
{
get
{
var bytes = Sdl.SDL_GetAudioStreamQueued(stream);
return bytes >= 0 ? bytes : throw new InvalidOperationException(Sdl.Error);
}
}
public SdlAudio(string path,bool loop=false,bool paused=false,bool muted=false)
{
this.loop=loop;
if(!Sdl.SDL_InitSubSystem(Sdl.InitAudio))throw new InvalidOperationException(Sdl.Error);
audioInitialized = true;
try
{
if(!Sdl.SDL_LoadWAV(Path.GetFullPath(path),out var spec,out data,out var size))throw new InvalidOperationException(Sdl.Error);
SourceFrequency=spec.Frequency;
length=checked((int)size);
stream=Sdl.SDL_OpenAudioDeviceStream(uint.MaxValue,ref spec,0,0);
if(stream==0)throw new InvalidOperationException(Sdl.Error);
Queue();
// SDL_OpenAudioDeviceStream starts paused. Keep it paused from its
// first sample when created while a debug menu has stopped playback.
Paused = true;
SetMuted(muted);
SetPaused(paused);
Console.WriteLine($"SDL3 WAV stream: {spec.Frequency} Hz, {spec.Channels} channel(s), {length} source bytes.");
}
catch{Dispose();throw;}
}
public void SetPaused(bool paused)
{
ObjectDisposedException.ThrowIf(stream == 0, this);
if (Paused == paused) return;
var changed = paused ? Sdl.SDL_PauseAudioStreamDevice(stream) : Sdl.SDL_ResumeAudioStreamDevice(stream);
if (!changed) throw new InvalidOperationException(Sdl.Error);
Paused = paused;
}
public void SetMuted(bool muted)
{
ObjectDisposedException.ThrowIf(stream == 0, this);
if (!Sdl.SDL_SetAudioStreamGain(stream, muted ? 0 : 1)) throw new InvalidOperationException(Sdl.Error);
Muted = muted;
}
public void SetFrequency(int frequency)
{
ObjectDisposedException.ThrowIf(stream==0,this);
if(frequency<=0||!Sdl.SDL_SetAudioStreamFrequencyRatio(stream,(float)frequency/SourceFrequency))throw new InvalidOperationException(Sdl.Error);
}
private void Queue(){if(!Sdl.SDL_PutAudioStreamData(stream,data,length))throw new InvalidOperationException(Sdl.Error);}
public void Pump(){if(!Paused && loop && QueuedBytes<length)Queue();}
public void Dispose()
{
if(stream!=0){Sdl.SDL_DestroyAudioStream(stream);stream=0;}
if(data!=0){Sdl.SDL_free(data);data=0;}
if(audioInitialized){Sdl.SDL_QuitSubSystem(Sdl.InitAudio);audioInitialized=false;}
}
}