2

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.

sonne
  • 377
  • 5
  • 20
Alexander Mashin
  • 693
  • 3
  • 14
  • 34

1 Answers1

2

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#

Community
  • 1
  • 1
sonne
  • 377
  • 5
  • 20