tim
tim

Reputation: 1369

Mute SoundPlayer for just my app

I wish to mute the sound for only my WPF application and leave the overall mixer as the user had it set.

I can mute/unmute the system wide sound using the following code.

But I notice when my app is running and a sound is playing, my app appears in the windows mixer and I can mute/unmute just my app via the mixer's UI so it seems like it should be possible for my app to do it programmatically.

private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
private const int WM_APPCOMMAND = 0x319;

[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr) APPCOMMAND_VOLUME_MUTE);

Upvotes: 2

Views: 3556

Answers (2)

Stealth Rabbi
Stealth Rabbi

Reputation: 10346

If you wrap the calls to play sounds, you can have these functions check some resource to indicate if the user has chosen to mute the sound or not, e.g. :

public void PlaySoundXYZ() 
{
   if(!MuteSource.IsMuted()) 
   {
        // play sound.
   }
}

Upvotes: 0

Naresh Jois
Naresh Jois

Reputation: 844

This works in Vista/7/8 where there is per application volume control

DllImport("winmm.dll")]
private static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);

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

/// <summary>
/// Returns volume from 0 to 10
/// </summary>
/// <returns>Volume from 0 to 10</returns>
public static int GetVolume()
{
  uint CurrVol = 0;
  waveOutGetVolume(IntPtr.Zero, out CurrVol);
  ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
  int volume = CalcVol / (ushort.MaxValue / 10);
  return volume;
}

/// <summary>
/// Sets volume from 0 to 10
/// </summary>
/// <param name="volume">Volume from 0 to 10</param>
public static void SetVolume(int volume)
{
  int NewVolume = ((ushort.MaxValue / 10) * volume);
  uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
  waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
}

Upvotes: 6

Related Questions