using CSCore; using CSCore.Codecs.OGG; using CSCore.CoreAudioAPI; using CSCore.SoundOut; using System; using System.IO; namespace BeatLyrics.Tool.Utils { internal static class OggAudioPlayer { private static readonly ISoundOut SoundOut; private static IWaveSource _waveSource; static OggAudioPlayer() { using var mmDeviceEnumerator = new MMDeviceEnumerator(); SoundOut = new WasapiOut { Latency = 1, Device = mmDeviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia) }; } public static void LoadOggFile(string path) { Unload(); var ms = new MemoryStream(File.ReadAllBytes(path)); _waveSource = new OggSource(ms).ToWaveSource(); SoundOut.Initialize(_waveSource); } public static void Play() => SoundOut.Play(); public static void Stop() => SoundOut.Stop(); public static void Unload() { if (_waveSource != null) { if (SoundOut.PlaybackState != PlaybackState.Stopped) SoundOut.Stop(); _waveSource?.Dispose(); _waveSource = null; } } public static TimeSpan Position { get => _waveSource.GetPosition(); set { if (value <= TimeSpan.Zero) _waveSource.SetPosition(TimeSpan.Zero); else { var len = _waveSource.GetLength(); _waveSource.SetPosition(value > len ? len.Add(TimeSpan.FromMilliseconds(-1)) : value.Add(TimeSpan.FromMilliseconds(-1))); } } } public static TimeSpan Length => _waveSource.GetLength(); public static bool IsPlaying => SoundOut.PlaybackState == PlaybackState.Playing; } }