SystemAudioVolumeInterop.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Reflection.PortableExecutable;
  2. using System.Runtime.InteropServices;
  3. using NAudio.CoreAudioApi;
  4. namespace SinMaiLauncher.Interops
  5. {
  6. public class SystemAudioVolumeInterop
  7. {
  8. /// <summary>
  9. /// 设置系统音量(0-100)
  10. /// </summary>
  11. /// <param name="value">音量百分比,范围 0-100</param>
  12. /// <returns>是否成功</returns>
  13. public static bool SetVolume(float value)
  14. {
  15. try
  16. {
  17. var setValue = value / 100f;
  18. // 创建 MMDeviceEnumerator 来访问音频设备
  19. using var enumerator = new MMDeviceEnumerator();
  20. // 获取默认音频输出设备
  21. using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
  22. // 获取 AudioEndpointVolume 对象
  23. using var volume = device.AudioEndpointVolume;
  24. volume.MasterVolumeLevelScalar = setValue;
  25. return true;
  26. }
  27. catch (Exception)
  28. {
  29. return false;
  30. }
  31. }
  32. /// <summary>
  33. /// 获取当前系统音量(0-100)
  34. /// </summary>
  35. /// <returns>音量百分比,失败时返回 -1</returns>
  36. public static float? GetVolume()
  37. {
  38. try
  39. {
  40. // 创建 MMDeviceEnumerator 来访问音频设备
  41. using var enumerator = new MMDeviceEnumerator();
  42. // 获取默认音频输出设备
  43. using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
  44. // 获取 AudioEndpointVolume 对象
  45. using var volume = device.AudioEndpointVolume;
  46. // 获取当前音量 (0.0f 到 1.0f)
  47. var currentVolume = volume.MasterVolumeLevelScalar;
  48. return (int)(currentVolume * 100);
  49. }
  50. catch (Exception e)
  51. {
  52. return null;
  53. }
  54. }
  55. }
  56. }