2009-05-27 63 views
4

是否有一種簡單的方法來設置來自託管.NET代碼的音量?從.net代碼更改音量

+0

您想調整系統音量嗎?你是否真的從你的應用程序播放音頻 - 如果是,使用什麼? – Noldorin 2009-05-27 12:31:36

+0

我不是在播放音頻。 – 2009-05-27 12:34:33

回答

1

This CodeProject article演示如何完全控制Windows混音設置,包括主音量的系統。它似乎包裝了大部分可怕的Win API,所以它可能是最簡單的方法。

1

簡單的答案:你必須使用互操作。

我寫了一個庫,做各種聲音的東西給你,壽:

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

+1

該庫似乎很好,但代碼示例會非常有幫助。你能補充一些嗎? – 2011-12-02 15:34:33

4

這會爲我的Windows 7:

下載n音訊(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); 
     }