Is there an easy way to set the volume from managed .net code?
Asked
Active
Viewed 7,370 times
4
-
You want to adjust the system volume? Are you actually playing audio from your application - if so, using what? – Noldorin May 27 '09 at 12:31
4 Answers
4
This does it for my Windows 7:
Download NAudio (http://naudio.codeplex.com/releases/view/79035) and reference the DLL in your project. Than add the following code:
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);
}

Mike de Klerk
- 11,906
- 8
- 54
- 76
1
This CodeProject article demonstrates how you fully control the Windows Mixer settings, including the master volume for the system. It seems to wrap most of the horrible Win API stuff, so it's probably the easiest way to go.

Noldorin
- 144,213
- 56
- 264
- 302
1
Simple answer: You have to use interop.
I wrote a library to do all kinds of sound stuff for you, tho:
WinnMM.Net: http://winmm.codeplex.com/

John Gietzen
- 48,783
- 32
- 145
- 190
-
1The library seems fine, but code samples would be really helpful. Could you please add some? – Vasyl Boroviak Dec 02 '11 at 15:34