Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Sound Volume from .net code

Tags:

.net

audio

volume

Is there an easy way to set the volume from managed .net code?

like image 960
Ronnie Overby Avatar asked Jan 23 '23 14:01

Ronnie Overby


1 Answers

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);
        }
like image 153
Mike de Klerk Avatar answered Jan 31 '23 03:01

Mike de Klerk