如果是winform,比较简单,发个消息即可:
const int APPCOMMAND_VOLUME_MUTE = 0x80000; const int WM_APPCOMMAND = 0x319; [DllImport("user32.dll")] static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); private void Mute() { SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE); }
如果是控制台程序,则比较麻烦,需要用COM,找了个Codeplex的项目 https://archive.codeplex.com/?p=netcoreaudio (2021年7月将关闭!),稍微修改了一下代码:
using Vannatech.CoreAudio.Interfaces; using Vannatech.CoreAudio.Constants; using Vannatech.CoreAudio.Structures; using Vannatech.CoreAudio.Enumerations; using Vannatech.CoreAudio.Externals; const string IAudioEndpointVolumeIID = "5CDF2C82-841E-4546-9722-0CF74078229A"; public class DeviceActivation { public IMMDevice MMDevice { get; set; } public string Id { get; set; } public IAudioEndpointVolume ActiveInterface { get; set; } } static void Main(string[] args) { object objInstance = null; var iid = new Guid(IAudioEndpointVolumeIID); DeviceActivation activation = null; try { var deviceEnumeratorType = Type.GetTypeFromCLSID(new Guid(ComCLSIDs.MMDeviceEnumeratorCLSID)); var deviceEnumerator = (IMMDeviceEnumerator)Activator.CreateInstance(deviceEnumeratorType); IMMDeviceCollection deviceCollection; deviceEnumerator.EnumAudioEndpoints(EDataFlow.eAll, DEVICE_STATE_XXX.DEVICE_STATEMASK_ALL, out deviceCollection); UInt32 deviceCount; deviceCollection.GetCount(out deviceCount); var deviceList = new List<IMMDevice>(); IMMDevice device = null; string deviceId = null; for (uint i = 0; i < deviceCount; i++) { deviceCollection.Item(i, out device); device.GetId(out deviceId); if (deviceId == "{0.0.0.00000000}.{568726bc-cd16-4c9e-a569-f625b5d5b499}") { var result = device.Activate(iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, IntPtr.Zero, out objInstance); break; } } if (objInstance != null) { activation = new DeviceActivation { MMDevice = device, Id = deviceId, ActiveInterface = (IAudioEndpointVolume)objInstance }; } bool muteOrig, muteNew; if (activation != null) { activation.ActiveInterface.GetMute(out muteOrig); if (!muteOrig) { muteNew = !muteOrig; Guid context = Guid.NewGuid(); var result = activation.ActiveInterface.SetMute(muteNew, context); } } } catch (Exception ex) { } finally { if (activation != null) { Marshal.FinalReleaseComObject(activation.MMDevice); Marshal.FinalReleaseComObject(activation.ActiveInterface); } } }
这里的{0.0.0.00000000}.{568726bc-cd16-4c9e-a569-f625b5d5b499}是调试出来的,不同的机器有可能不同。