【问题标题】:Mute/unmute, Change master volume in Windows 7 x64 with C#静音/取消静音,使用 C# 在 Windows 7 x64 中更改主音量
【发布时间】:2011-02-28 11:37:24
【问题描述】:

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

我已经看到使用 winmm.dll here 的出色实现,但它适用于 XP 而不适用于 Windows 7。

【问题讨论】:

标签: c# windows-7 windows-7-x64


【解决方案1】:

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

支持的最低客户端:Windows Vista

最低支持服务器:Windows Server 2008

【讨论】:

  • 非常好,我测试了它,它在 Windows 7 x64 中工作。非常感谢!
  • codeproject 文章已被删除 :( 有谁可以在这里插入代码吗?
  • 此答案包含一些代码(可能不是已删除的 codeproject 文章中的代码,但至少它包含基本的 COM 接口和定义):stackoverflow.com/a/14322736/356716
【解决方案2】:

我用这个代码成功地使用了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);
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 2013-10-15
    • 2013-09-15
    • 1970-01-01
    相关资源
    最近更新 更多