Change SYSTEM volume level in windows

13,031

Here is the easiest and well known method using P/Invoke calls:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;

    namespace VolumeControl
    {
       public partial class Form1 : Form
       {
          [DllImport("winmm.dll")]
          public static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);

      [DllImport("winmm.dll")]
      public static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);

      public Form1()
      {
         InitializeComponent();
         // By the default set the volume to 0
         uint CurrVol = 0;
         // At this point, CurrVol gets assigned the volume
         waveOutGetVolume(IntPtr.Zero, out CurrVol);
         // Calculate the volume
         ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
         // Get the volume on a scale of 1 to 10 (to fit the trackbar)
         trackWave.Value = CalcVol / (ushort.MaxValue / 10);
      }

      private void trackWave_Scroll(object sender, EventArgs e)
      {
         // Calculate the volume that's being set
         int NewVolume = ((ushort.MaxValue / 10) * trackWave.Value);
         // Set the same volume for both the left and the right channels
         uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
         // Set the volume
         waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
      }
   }
}

Source: http://www.geekpedia.com/tutorial176_Get-and-set-the-wave-sound-volume.html

Also, if you wish to combine this to work with CoreAudioAPI - read this: Change master audio volume from XP to Windows 8 in C#

Share:
13,031
Alexander Mashin
Author by

Alexander Mashin

Updated on June 04, 2022

Comments

  • Alexander Mashin
    Alexander Mashin almost 2 years

    My application needs to be able to change system volume levels for sound devices. I'm using C# with NAudio. I tried using CoreAudio Api in NAudio, but this don't work in Windows XP, however my program needs to support XP. Please help me, what do I need to use, to get my program to support XP as well as the latest Windows.

  • BrunoLM
    BrunoLM over 10 years
    I am on Windows 8.1. Regardless of my audio levels I always get the same value (65535), even if I mute the master volume.
  • kritzikratzi
    kritzikratzi over 10 years
    in windows 7 this only reads/writes the per-application volume