AudioService.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Threading.Tasks;
  6. namespace SlamCross.Services;
  7. public record AudioDevice(int Index, string Name, string PactlId = "");
  8. public interface IAudioService : IDisposable
  9. {
  10. List<AudioDevice> GetOutputDevices();
  11. List<AudioDevice> GetInputDevices();
  12. void Play(string filePath, int deviceIndex, float volume = 1.0f, int startSampleBytes = 0, int endSampleBytes = 0, string pactlId = "");
  13. void Stop();
  14. }
  15. public class LinuxAudioService : IAudioService
  16. {
  17. private Process? _ffmpegProc;
  18. private Process? _pacatProc;
  19. public List<AudioDevice> GetOutputDevices() => ParsePactl("sinks");
  20. public List<AudioDevice> GetInputDevices() => ParsePactl("sources");
  21. public void Play(string filePath, int deviceIndex, float volume = 1.0f, int startSampleBytes = 0, int endSampleBytes = 0, string pactlId = "")
  22. {
  23. Stop();
  24. string sinkId = pactlId;
  25. if (string.IsNullOrEmpty(sinkId))
  26. {
  27. var devices = GetOutputDevices();
  28. sinkId = deviceIndex >= 0 && deviceIndex < devices.Count ? devices[deviceIndex].PactlId : "";
  29. }
  30. var absPath = Path.GetFullPath(filePath);
  31. var ffmpegPsi = new ProcessStartInfo("ffmpeg") { UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true };
  32. if (startSampleBytes > 0)
  33. {
  34. ffmpegPsi.ArgumentList.Add("-ss");
  35. ffmpegPsi.ArgumentList.Add(BytesToSec(startSampleBytes).ToString("F5"));
  36. }
  37. ffmpegPsi.ArgumentList.Add("-i"); ffmpegPsi.ArgumentList.Add(absPath);
  38. if (endSampleBytes > startSampleBytes && endSampleBytes > 0)
  39. {
  40. ffmpegPsi.ArgumentList.Add("-t");
  41. ffmpegPsi.ArgumentList.Add(BytesToSec(endSampleBytes - startSampleBytes).ToString("F5"));
  42. }
  43. if (Math.Abs(volume - 1.0f) >= 0.001f)
  44. {
  45. ffmpegPsi.ArgumentList.Add("-af");
  46. ffmpegPsi.ArgumentList.Add($"volume={Math.Pow(volume, 2):F5}");
  47. }
  48. ffmpegPsi.ArgumentList.Add("-f"); ffmpegPsi.ArgumentList.Add("s16le");
  49. ffmpegPsi.ArgumentList.Add("-ar"); ffmpegPsi.ArgumentList.Add("48000");
  50. ffmpegPsi.ArgumentList.Add("-ac"); ffmpegPsi.ArgumentList.Add("1");
  51. ffmpegPsi.ArgumentList.Add("-loglevel"); ffmpegPsi.ArgumentList.Add("quiet");
  52. ffmpegPsi.ArgumentList.Add("pipe:1");
  53. var pacatPsi = new ProcessStartInfo("pacat") { UseShellExecute = false, RedirectStandardInput = true, CreateNoWindow = true };
  54. pacatPsi.ArgumentList.Add("--playback");
  55. pacatPsi.ArgumentList.Add("--rate=48000");
  56. pacatPsi.ArgumentList.Add("--channels=1");
  57. pacatPsi.ArgumentList.Add("--format=s16le");
  58. if (!string.IsNullOrEmpty(sinkId)) { pacatPsi.ArgumentList.Add("--device"); pacatPsi.ArgumentList.Add(sinkId); }
  59. _ffmpegProc = Process.Start(ffmpegPsi)!;
  60. _pacatProc = Process.Start(pacatPsi)!;
  61. var ffOut = _ffmpegProc.StandardOutput.BaseStream;
  62. var paIn = _pacatProc.StandardInput.BaseStream;
  63. Task.Run(async () =>
  64. {
  65. try { await ffOut.CopyToAsync(paIn); } catch { }
  66. try { paIn.Close(); } catch { }
  67. });
  68. }
  69. private static double BytesToSec(int sampleBytes) => sampleBytes / (22050.0 * 2);
  70. public void Stop()
  71. {
  72. try { _ffmpegProc?.Kill(); } catch { }
  73. try { _pacatProc?.Kill(); } catch { }
  74. try { _ffmpegProc?.Dispose(); } catch { }
  75. try { _pacatProc?.Dispose(); } catch { }
  76. _ffmpegProc = null;
  77. _pacatProc = null;
  78. }
  79. private static List<AudioDevice> ParsePactl(string type)
  80. {
  81. try
  82. {
  83. var psi = new ProcessStartInfo("pactl", $"list {type}")
  84. {
  85. RedirectStandardOutput = true,
  86. UseShellExecute = false,
  87. CreateNoWindow = true
  88. };
  89. using var proc = Process.Start(psi);
  90. var output = proc?.StandardOutput.ReadToEnd() ?? "";
  91. var devices = new List<AudioDevice>();
  92. string? currentName = null;
  93. string? currentDesc = null;
  94. int idx = 0;
  95. foreach (var line in output.Split('\n'))
  96. {
  97. var trimmed = line.Trim();
  98. if (trimmed.StartsWith("Name: "))
  99. currentName = trimmed["Name: ".Length..];
  100. else if (trimmed.StartsWith("Description: "))
  101. currentDesc = trimmed["Description: ".Length..];
  102. if (currentName != null && currentDesc != null)
  103. {
  104. devices.Add(new AudioDevice(idx++, currentDesc, currentName));
  105. currentName = null;
  106. currentDesc = null;
  107. }
  108. }
  109. return devices;
  110. }
  111. catch { return new List<AudioDevice>(); }
  112. }
  113. public void Dispose() => Stop();
  114. }
  115. #if WINDOWS
  116. public class WindowsAudioService : IAudioService
  117. {
  118. private NAudio.Wave.WaveOutEvent? _waveOut;
  119. public List<AudioDevice> GetOutputDevices()
  120. {
  121. var list = new List<AudioDevice>();
  122. int count = NAudio.Wave.WaveInterop.waveOutGetNumDevs();
  123. int size = System.Runtime.InteropServices.Marshal.SizeOf<NAudio.Wave.WaveOutCapabilities>();
  124. for (int i = 0; i < count; i++)
  125. {
  126. NAudio.Wave.WaveInterop.waveOutGetDevCaps((IntPtr)i, out var caps, size);
  127. list.Add(new AudioDevice(i, caps.ProductName));
  128. }
  129. return list;
  130. }
  131. public List<AudioDevice> GetInputDevices()
  132. {
  133. var list = new List<AudioDevice>();
  134. for (int i = 0; i < NAudio.Wave.WaveInEvent.DeviceCount; i++)
  135. {
  136. var caps = NAudio.Wave.WaveInEvent.GetCapabilities(i);
  137. list.Add(new AudioDevice(i, caps.ProductName));
  138. }
  139. return list;
  140. }
  141. public void Play(string filePath, int deviceIndex, float volume = 1.0f, int startSampleBytes = 0, int endSampleBytes = 0, string pactlId = "")
  142. {
  143. Stop();
  144. NAudio.Wave.WaveStream reader;
  145. if (Math.Abs(volume - 1.0f) < 0.001f && startSampleBytes <= 0 && endSampleBytes <= 0)
  146. {
  147. reader = new NAudio.Wave.AudioFileReader(filePath);
  148. }
  149. else
  150. {
  151. var wave = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(filePath));
  152. if (Math.Abs(volume - 1.0f) >= 0.001f)
  153. wave.Volume = (float)Math.Pow(volume, 2);
  154. if (endSampleBytes > 0 && endSampleBytes > startSampleBytes)
  155. {
  156. int byteCount = (endSampleBytes - startSampleBytes) * 4;
  157. var buf = new byte[byteCount];
  158. wave.Position = startSampleBytes * 4;
  159. wave.Read(buf, 0, byteCount);
  160. wave = new NAudio.Wave.WaveChannel32(
  161. new NAudio.Wave.RawSourceWaveStream(new MemoryStream(buf), wave.WaveFormat));
  162. }
  163. wave.PadWithZeroes = false;
  164. reader = wave;
  165. }
  166. _waveOut = new NAudio.Wave.WaveOutEvent { DeviceNumber = deviceIndex };
  167. _waveOut.Init(reader);
  168. _waveOut.Play();
  169. }
  170. public void Stop()
  171. {
  172. _waveOut?.Stop();
  173. _waveOut?.Dispose();
  174. _waveOut = null;
  175. }
  176. public void Dispose() => Stop();
  177. }
  178. #endif
  179. public static class AudioServiceFactory
  180. {
  181. public static IAudioService Create()
  182. {
  183. #if WINDOWS
  184. return new WindowsAudioService();
  185. #else
  186. return new LinuxAudioService();
  187. #endif
  188. }
  189. }