AudioService.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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.WaveOut? _waveOut;
  119. public List<AudioDevice> GetOutputDevices()
  120. {
  121. var list = new List<AudioDevice>();
  122. for (int i = 0; i < NAudio.Wave.WaveOut.DeviceCount; i++)
  123. {
  124. var caps = NAudio.Wave.WaveOut.GetCapabilities(i);
  125. list.Add(new AudioDevice(i, caps.ProductName));
  126. }
  127. return list;
  128. }
  129. public List<AudioDevice> GetInputDevices()
  130. {
  131. var list = new List<AudioDevice>();
  132. for (int i = 0; i < NAudio.Wave.WaveIn.DeviceCount; i++)
  133. {
  134. var caps = NAudio.Wave.WaveIn.GetCapabilities(i);
  135. list.Add(new AudioDevice(i, caps.ProductName));
  136. }
  137. return list;
  138. }
  139. public void Play(string filePath, int deviceIndex, float volume = 1.0f, int startSampleBytes = 0, int endSampleBytes = 0, string pactlId = "")
  140. {
  141. Stop();
  142. NAudio.Wave.WaveStream reader;
  143. if (Math.Abs(volume - 1.0f) < 0.001f && startSampleBytes <= 0 && endSampleBytes <= 0)
  144. {
  145. reader = new NAudio.Wave.AudioFileReader(filePath);
  146. }
  147. else
  148. {
  149. var wave = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(filePath));
  150. if (Math.Abs(volume - 1.0f) >= 0.001f)
  151. wave.Volume = (float)Math.Pow(volume, 2);
  152. if (endSampleBytes > 0 && endSampleBytes > startSampleBytes)
  153. {
  154. int byteCount = (endSampleBytes - startSampleBytes) * 4;
  155. var buf = new byte[byteCount];
  156. wave.Position = startSampleBytes * 4;
  157. wave.Read(buf, 0, byteCount);
  158. wave = new NAudio.Wave.WaveChannel32(
  159. new NAudio.Wave.RawSourceWaveStream(new MemoryStream(buf), wave.WaveFormat));
  160. }
  161. wave.PadWithZeroes = false;
  162. reader = wave;
  163. }
  164. _waveOut = new NAudio.Wave.WaveOut { DeviceNumber = deviceIndex };
  165. _waveOut.Init(reader);
  166. _waveOut.Play();
  167. }
  168. public void Stop()
  169. {
  170. _waveOut?.Stop();
  171. _waveOut?.Dispose();
  172. _waveOut = null;
  173. }
  174. public void Dispose() => Stop();
  175. }
  176. #endif
  177. public static class AudioServiceFactory
  178. {
  179. public static IAudioService Create()
  180. {
  181. #if WINDOWS
  182. return new WindowsAudioService();
  183. #else
  184. return new LinuxAudioService();
  185. #endif
  186. }
  187. }