如何在Windows 10中使用C#设置麦克风的“收听此设备”功能

实现方案
完全可以在Windows 10上通过C#切换麦克风的「收听此设备」设置,不需要修改注册表,直接调用Windows Core Audio API即可实现,你正在使用的AudioSwitcher.AudioApi.CoreAudio库可以直接扩展支持该功能。
1. 基于现有AudioSwitcher库扩展实现(推荐)
前置依赖
首先确认已安装NuGet包:Install-Package AudioSwitcher.AudioApi.CoreAudio
代码实现
首先补充未封装的原生COM接口声明:
using AudioSwitcher.AudioApi.CoreAudio; using System.Runtime.InteropServices; [Flags] public enum ClsCtx : uint { InProcServer = 0x1, InProcHandler = 0x2, LocalServer = 0x4, RemoteServer = 0x10, All = InProcServer | InProcHandler | LocalServer | RemoteServer } [ComImport] [Guid("784CFD40-9F89-456E-A16C-4369B8976B74")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAudioEndpoint2 { // 占位方法,保证接口偏移量正确即可,无需实现 void Placeholder1(); void Placeholder2(); void Placeholder3(); /// <summary> /// 设置收听状态 /// </summary> /// <param name="enable">true=开启收听,false=关闭收听</param> /// <param name="reserved">保留参数,传Guid.Empty即可</param> /// <returns>0代表调用成功</returns> int SetListenState(bool enable, Guid reserved); /// <summary> /// 获取当前收听状态 /// </summary> int GetListenState(out bool enabled, out Guid reserved); }
然后编写切换逻辑:
public static void SetMicrophoneListenState(string micDeviceName, bool enableListen) { var audioController = new CoreAudioController(); // 查找目标麦克风设备 var targetMic = audioController.GetCaptureDevices() .FirstOrDefault(dev => dev.FullName.Contains(micDeviceName)); if (targetMic == null) { throw new KeyNotFoundException("未找到指定的麦克风设备"); } // 激活原生IAudioEndpoint2接口 var nativeMmDevice = (MMDevice)targetMic.GetType() .GetProperty("NativeDevice", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance) .GetValue(targetMic); var endpoint2 = nativeMmDevice.Activate( typeof(IAudioEndpoint2).GUID, ClsCtx.All, IntPtr.Zero) as IAudioEndpoint2; if (endpoint2 == null) { throw new NotSupportedException("当前设备不支持收听功能"); } // 执行设置操作 int result = endpoint2.SetListenState(enableListen, Guid.Empty); if (result != 0) { throw new UnauthorizedAccessException("设置失败,请确保程序以管理员权限运行"); } }
注意事项
- 程序必须以管理员权限运行,否则会触发权限不足错误
- 修改即时生效,不需要重启系统或音频服务
- 部分虚拟音频设备可能不支持该接口,可先调用
GetListenState判断兼容性
2. 注册表修改方案(不推荐)
修改对应设备的注册表项也可以实现,路径为:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture\{麦克风设备GUID}\Properties
目标属性为{9855C4CD-DF8C-446C-8E8C-23BCD188A72E},2,值为1代表开启,0代表关闭。
但该方案修改后需要重启Windows音频服务Audiosrv才能生效,且容易出现权限异常,因此不建议使用。
内容的提问来源于stack exchange,提问作者Fellnase
相关产品推荐
相关产品推荐

