从.net代码更改音量

时间:2009-05-27 12:28:52

标签: .net audio volume

是否有一种从托管.net代码设置卷的简单方法?

4 个答案:

答案 0 :(得分:4)

这适用于我的Windows 7:

下载NAudio(http://naudio.codeplex.com/releases/view/79035)并在您的项目中引用DLL。然后添加以下代码:

        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
                {
                    //Set at maximum volume
                    dev.AudioEndpointVolume.MasterVolumeLevel = 0;

                    //Get its audio volume
                    System.Diagnostics.Debug.Print("Volume of " + dev.FriendlyName + " is " + dev.AudioEndpointVolume.MasterVolumeLevel.ToString());

                    //Mute it
                    dev.AudioEndpointVolume.Mute = true;
                    System.Diagnostics.Debug.Print(dev.FriendlyName + " is muted");
                }
                catch (Exception ex)
                {
                    //Do something with exception when an audio endpoint could not be muted
                    System.Diagnostics.Debug.Print(dev.FriendlyName + " could not be muted");
                }
            }
        }
        catch (Exception ex)
        {
            //When something happend that prevent us to iterate through the devices
            System.Diagnostics.Debug.Print("Could not enumerate devices due to an excepion: " + ex.Message);
        }

答案 1 :(得分:2)

这篇相当长的文章展示了如何:Controlling sound volume in C#

答案 2 :(得分:1)

This CodeProject article演示了如何完全控制Windows Mixer设置,包括系统的主卷。它似乎包含了大部分可怕的Win API内容,因此它可能是最简单的方法。

答案 3 :(得分:1)

简单回答:你必须使用互操作。

我写了一个库,为你做各种声音的东西,你好:

WinnMM.Net:http://winmm.codeplex.com/