Change program's volume on Win 7

Devator picture Devator · Apr 23, 2012 · Viewed 7.1k times · Source

I want to change the program's volume (and not master volume). I have the following code right now:

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);

private void volumeBar_Scroll(object sender, EventArgs e)
{
    // Calculate the volume that's being set
    int NewVolume = ((ushort.MaxValue / 10) * volumeBar.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);
}

This only works on Win XP, not Windows 7 (and probably Vista neither). I've not found any script that will achieve the same on Win 7, only to change the master volume (which I am not after).

Answer

Phil picture Phil · Apr 25, 2012

Your code worked ok for me (with a couple of tweaks). Here's the code for a very simple WPF test app running on Windows 7 x64:

Xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Slider Minimum="0" Maximum="10" ValueChanged="ValueChanged"/>
    </Grid>
</Window>

C#

public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
        // Calculate the volume that's being set
        double newVolume = ushort.MaxValue * e.NewValue / 10.0;

        uint v = ((uint) newVolume) & 0xffff;
        uint vAll = v | (v << 16);

        // Set the volume
        int retVal = NativeMethods.WaveOutSetVolume(IntPtr.Zero, vAll);

        Debug.WriteLine(retVal);

        bool playRetVal = NativeMethods.PlaySound("tada.wav", IntPtr.Zero, 0x2001);

        Debug.WriteLine(playRetVal);
    }
}

static class NativeMethods
{
    [DllImport("winmm.dll", EntryPoint = "waveOutSetVolume")]
    public static extern int WaveOutSetVolume(IntPtr hwo, uint dwVolume);

    [DllImport("winmm.dll", SetLastError = true)]
    public static extern bool PlaySound(string pszSound, IntPtr hmod, uint fdwSound);
}

When I start the app and move the slider, then an additional volume control appears in the 'Volume Mixer' which moves from min to max synchronously with the slider.

You should examine the return value from waveOutSetVolume. It may give you a clue if your code still doesn't work.