123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- using System.Reflection.PortableExecutable;
- using System.Runtime.InteropServices;
- using NAudio.CoreAudioApi;
- namespace SinMaiLauncher.Interops
- {
- public class SystemAudioVolumeInterop
- {
- /// <summary>
- /// 设置系统音量(0-100)
- /// </summary>
- /// <param name="value">音量百分比,范围 0-100</param>
- /// <returns>是否成功</returns>
- 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;
- }
- }
- /// <summary>
- /// 获取当前系统音量(0-100)
- /// </summary>
- /// <returns>音量百分比,失败时返回 -1</returns>
- 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;
- }
- }
- }
- }
|