Files
ParsonsMasterSystem2026/Desktop/NAudioPlayer.cs

49 lines
1.5 KiB
C#

using System;
using Core.Interfaces;
using Microsoft.VisualBasic;
using NAudio.Wave;
namespace Desktop.Audio // Change this to match your project's namespace
{
public class NAudioPlayer : IAudioDevice
{
private WaveOutEvent _waveOut;
private BufferedWaveProvider _buffer;
public NAudioPlayer()
{
// Set up the audio format: 44100 Hz, 32-bit IEEE float, 1 channel (Mono)
WaveFormat format = WaveFormat.CreateIeeeFloatWaveFormat(44100, 1);
_buffer = new BufferedWaveProvider(format);
// CRITICAL FOR EMULATORS:
// If the emulator runs slightly too fast, the audio buffer will fill up
// and the sound will lag behind the gameplay. Discarding overflow keeps it synced!
_buffer.DiscardOnBufferOverflow = true;
_waveOut = new WaveOutEvent();
// 100ms latency is a great sweet spot for WinForms emulators.
// Too low = crackling audio. Too high = delayed sound effects.
_waveOut.DesiredLatency = 100;
_waveOut.Init(_buffer);
_waveOut.Play();
}
public void AddSample(float sample)
{
// Convert the float (-1.0f to 1.0f) into 4 raw bytes
byte[] sampleBytes = BitConverter.GetBytes(sample);
// Push the 4 bytes to the sound card buffer!
_buffer.AddSamples(sampleBytes, 0, 4);
}
public void Stop()
{
_waveOut?.Stop();
_waveOut?.Dispose();
}
}
}