OggAudioPlayer.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using CSCore;
  2. using CSCore.Codecs.OGG;
  3. using CSCore.CoreAudioAPI;
  4. using CSCore.SoundOut;
  5. using System;
  6. using System.IO;
  7. namespace BeatLyrics.Tool.Utils
  8. {
  9. internal static class OggAudioPlayer
  10. {
  11. private static readonly ISoundOut SoundOut;
  12. private static IWaveSource _waveSource;
  13. static OggAudioPlayer()
  14. {
  15. using var mmDeviceEnumerator = new MMDeviceEnumerator();
  16. SoundOut = new WasapiOut { Latency = 1, Device = mmDeviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia) };
  17. }
  18. public static void LoadOggFile(string path)
  19. {
  20. Unload();
  21. var ms = new MemoryStream(File.ReadAllBytes(path));
  22. _waveSource = new OggSource(ms).ToWaveSource();
  23. SoundOut.Initialize(_waveSource);
  24. }
  25. public static void Play() => SoundOut.Play();
  26. public static void Stop() => SoundOut.Stop();
  27. public static void Unload()
  28. {
  29. if (_waveSource != null)
  30. {
  31. if (SoundOut.PlaybackState != PlaybackState.Stopped) SoundOut.Stop();
  32. _waveSource?.Dispose();
  33. _waveSource = null;
  34. }
  35. }
  36. public static TimeSpan Position
  37. {
  38. get => _waveSource.GetPosition();
  39. set
  40. {
  41. if (value <= TimeSpan.Zero) _waveSource.SetPosition(TimeSpan.Zero);
  42. else
  43. {
  44. var len = _waveSource.GetLength();
  45. _waveSource.SetPosition(value > len ? len.Add(TimeSpan.FromMilliseconds(-1)) : value.Add(TimeSpan.FromMilliseconds(-1)));
  46. }
  47. }
  48. }
  49. public static TimeSpan Length => _waveSource.GetLength();
  50. public static bool IsPlaying => SoundOut.PlaybackState == PlaybackState.Playing;
  51. }
  52. }