Jan Jan - 1 year ago 202
C# Question

Process volume and trackbar

I have a trackbar in my form that has a range of 1-100 (for volume). I am looking for a way to set the audio output volume to a value I've entered (e.g. trackbar's value) but ONLY for my application.

Didn't find something in the web.


Answer Source
private void trackBar1_ValueChanged(object sender, EventArgs e)

        // Calculate the volume that's being set
        double newVolume = ushort.MaxValue * trackBar1.Value/ 10.0;

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

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

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


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

This should simply work. i hope i didnt miss anything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download