8

如何使用 C# 在 Windows 7 中调整主音量?

我在这里看到了使用 winmm.dll 的出色实现,但它适用于 XP 而不适用于 Windows 7。

4

2 回答 2

11

我使用以下代码成功使用了nuget包Naudio:

public void SetVolume(int level)
   {
            try
            {
                //Instantiate an Enumerator to find audio devices
                    NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator();
                        //Get all the devices, no matter what condition or status
                NAudio.CoreAudioApi.MMDeviceCollection DevCol = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.All);
                //Loop through all devices
                foreach (NAudio.CoreAudioApi.MMDevice dev in DevCol)
                {
                    try
                    {
                        if (dev.State == NAudio.CoreAudioApi.DeviceState.Active)
                        {
                            var newVolume = (float)Math.Max(Math.Min(level, 100),0) / (float)100;

                            //Set at maximum volume
                            dev.AudioEndpointVolume.MasterVolumeLevelScalar = newVolume;

                            dev.AudioEndpointVolume.Mute = level == 0;

                            //Get its audio volume
                            _log.Info("Volume of " + dev.FriendlyName + " is " + dev.AudioEndpointVolume.MasterVolumeLevelScalar.ToString());
                        }
                        else
                        {
                            _log.Debug("Ignoring device " + dev.FriendlyName + " with state " + dev.State);
                        }
                    }
                    catch (Exception ex)
                    {
                        //Do something with exception when an audio endpoint could not be muted
                        _log.Warn(dev.FriendlyName + " could not be muted with error " + ex);
                    }
                }
            }
            catch (Exception ex)
            {
                //When something happend that prevent us to iterate through the devices
                _log.Warn("Could not enumerate devices due to an excepion: " + ex.Message);
            }
        }
于 2015-04-27T08:46:47.770 回答
5

CodeProject在这里有一个很好的示例。请注意,它完全依赖于 COM 互操作(如果您对实现细节感兴趣,请查看 MSDN 上的IAudioEndpointVolumeIAudioMeterInformation等 COM 接口),并且仅适用于 Vista/Win7 及更高版本。

支持的最低客户端:Windows Vista

支持的最低服务器:Windows Server 2008

于 2010-06-06T23:45:29.337 回答