using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using NAudio.CoreAudioApi; namespace SinMaiLauncher.Interops { public class SystemAudioVolumeInterop { /// /// 设置系统音量(0-100) /// /// 音量百分比,范围 0-100 /// 是否成功 public static bool SetVolume(float value) { try { var setValue = value / 100f; // 创建 MMDeviceEnumerator 来访问音频设备 using var enumerator = new MMDeviceEnumerator(); // 获取默认音频输出设备 using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia); // 获取 AudioEndpointVolume 对象 using var volume = device.AudioEndpointVolume; volume.MasterVolumeLevelScalar = setValue; return true; } catch (Exception) { return false; } } /// /// 获取当前系统音量(0-100) /// /// 音量百分比,失败时返回 -1 public static float? GetVolume() { try { // 创建 MMDeviceEnumerator 来访问音频设备 using var enumerator = new MMDeviceEnumerator(); // 获取默认音频输出设备 using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia); // 获取 AudioEndpointVolume 对象 using var volume = device.AudioEndpointVolume; // 获取当前音量 (0.0f 到 1.0f) var currentVolume = volume.MasterVolumeLevelScalar; return (int)(currentVolume * 100); } catch (Exception e) { return null; } } } }