Mute Windows Volume Using C#

How to programmatically disable the sound?

on my computer.

Supposedly you want to mute or change volume on a device rather than for specific application. Or, you could have thought of all devices - you were not specific enough. All in all, the choice of API is an unlucky guess, instead you want Core Audio APIs.

From MSDN:

Audio applications that use the MMDevice API and WASAPI typically use the ISimpleAudioVolume interface to manage stream volume levels on a per-session basis. In rare cases, a specialized audio application might require the use of the IAudioEndpointVolume interface to control the master volume level of an audio endpoint device. A client of IAudioEndpointVolume must take care to avoid the potentially disruptive effects on other audio applications of altering the master volume levels of audio endpoint devices. Typically, the user has exclusive control over the master volume levels through the Windows volume-control program, Sndvol.exe.

This questions is a lead to look for API/interfaces of your interest: Where in the .NET class library is IAudioEndpointVolume located? Also, here is another one for you: Mute/unmute, Change master volume in Windows 7 x64 with C#

Mute/unmute, Change master volume in Windows 7 x64 with C#

CodeProject has a very good sample here. Note that it relies on COM interop completely (check COM interface like IAudioEndpointVolume and IAudioMeterInformation on MSDN if you are interested in implementation details), and works ONLY for Vista/Win7 and higher.

Minimum supported client: Windows Vista

Minimum supported server: Windows Server 2008

C# mute other application

Thanks you Make that 4 for the help.

The links you provided helped me find this answer,, which I modified a bit to fit my needs.

First of all, this answer requires the NuGet package CSCore.

This is an example code that I used (I am still learning the package):

public class MixerTest
{
static void Main(string[] args)
{
foreach (AudioSessionManager2 sessionManager in GetDefaultAudioSessionManager2(DataFlow.Render))
{
using (sessionManager)
{
using (var sessionEnumerator = sessionManager.GetSessionEnumerator())
{
foreach (var session in sessionEnumerator)
{
using var simpleVolume = session.QueryInterface<SimpleAudioVolume>();
using var sessionControl = session.QueryInterface<AudioSessionControl2>();
Console.WriteLine((sessionControl.Process.ProcessName, sessionControl.SessionIdentifier));
if (Process.GetProcessById(sessionControl.ProcessID).ProcessName.Equals("chrome"))
{
simpleVolume.IsMuted = true;
}
}
}
}
}

Console.ReadKey();
}
private static IEnumerable<AudioSessionManager2> GetDefaultAudioSessionManager2(DataFlow dataFlow)
{
using var enumerator = new MMDeviceEnumerator();
using var devices = enumerator.EnumAudioEndpoints(dataFlow, DeviceState.Active);
foreach (var device in devices)
{
Console.WriteLine("Device: " + device.FriendlyName);
var sessionManager = AudioSessionManager2.FromMMDevice(device);
yield return sessionManager;
}
}
}

Windows 10 Get System Audio Mute Status in C#

IAudioEndpointVolume is avalable in Windows Core Audio APIs .Net wrapper.

You can get whether master volume is muted or not by calling int GetMute([Out] [MarshalAs(UnmanagedType.Bool)] out Boolean isMuted) method:

// http://netcoreaudio.codeplex.com/SourceControl/latest#trunk/Code/CoreAudio/Interfaces/IAudioEndpointVolume.cs
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioEndpointVolume
{
/// <summary>
/// Gets the muting state of the audio stream.
/// </summary>
/// <param name="isMuted">The muting state. True if the stream is muted, false otherwise.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int GetMute([Out] [MarshalAs(UnmanagedType.Bool)] out Boolean isMuted);
}

I have created simple realization of GetMute function (and all necessary interfaces abstractions from Windows CoreAudio API).

AudioManager class code:

public static class AudioManager
{
/// <summary>
/// Gets the mute state of the master volume.
/// While the volume can be muted the <see cref="GetMasterVolume"/> will still return the pre-muted volume value.
/// </summary>
/// <returns>false if not muted, true if volume is muted</returns>
public static bool GetMasterVolumeMute()
{
IAudioEndpointVolume masterVol = null;
try
{
masterVol = GetMasterVolumeObject();
if (masterVol == null)
return false;

bool isMuted;
masterVol.GetMute(out isMuted);
return isMuted;
}
finally
{
if (masterVol != null)
Marshal.ReleaseComObject(masterVol);
}
}

private static IAudioEndpointVolume GetMasterVolumeObject()
{
IMMDeviceEnumerator deviceEnumerator = null;
IMMDevice speakers = null;
try
{
deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);

Guid IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID;
object o;
speakers.Activate(ref IID_IAudioEndpointVolume, 0, IntPtr.Zero, out o);
IAudioEndpointVolume masterVol = (IAudioEndpointVolume)o;

return masterVol;
}
finally
{
if (speakers != null) Marshal.ReleaseComObject(speakers);
if (deviceEnumerator != null) Marshal.ReleaseComObject(deviceEnumerator);
}
}

#region Abstracted COM interfaces from Windows CoreAudio API

[ComImport]
[Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
internal class MMDeviceEnumerator
{
}

internal enum EDataFlow
{
eRender,
eCapture,
eAll,
EDataFlow_enum_count
}

internal enum ERole
{
eConsole,
eMultimedia,
eCommunications,
ERole_enum_count
}

[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IMMDeviceEnumerator
{
int NotImpl1();

[PreserveSig]
int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice ppDevice);
}

[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IMMDevice
{
[PreserveSig]
int Activate(ref Guid iid, int dwClsCtx, IntPtr pActivationParams, [MarshalAs(UnmanagedType.IUnknown)] out object ppInterface);
}

// http://netcoreaudio.codeplex.com/SourceControl/latest#trunk/Code/CoreAudio/Interfaces/IAudioEndpointVolume.cs
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioEndpointVolume
{
[PreserveSig]
int NotImpl1();

[PreserveSig]
int NotImpl2();

/// <summary>
/// Gets a count of the channels in the audio stream.
/// </summary>
/// <param name="channelCount">The number of channels.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int GetChannelCount(
[Out] [MarshalAs(UnmanagedType.U4)] out UInt32 channelCount);

/// <summary>
/// Sets the master volume level of the audio stream, in decibels.
/// </summary>
/// <param name="level">The new master volume level in decibels.</param>
/// <param name="eventContext">A user context value that is passed to the notification callback.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int SetMasterVolumeLevel(
[In] [MarshalAs(UnmanagedType.R4)] float level,
[In] [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);

/// <summary>
/// Sets the master volume level, expressed as a normalized, audio-tapered value.
/// </summary>
/// <param name="level">The new master volume level expressed as a normalized value between 0.0 and 1.0.</param>
/// <param name="eventContext">A user context value that is passed to the notification callback.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int SetMasterVolumeLevelScalar(
[In] [MarshalAs(UnmanagedType.R4)] float level,
[In] [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);

/// <summary>
/// Gets the master volume level of the audio stream, in decibels.
/// </summary>
/// <param name="level">The volume level in decibels.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int GetMasterVolumeLevel(
[Out] [MarshalAs(UnmanagedType.R4)] out float level);

/// <summary>
/// Gets the master volume level, expressed as a normalized, audio-tapered value.
/// </summary>
/// <param name="level">The volume level expressed as a normalized value between 0.0 and 1.0.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int GetMasterVolumeLevelScalar(
[Out] [MarshalAs(UnmanagedType.R4)] out float level);

/// <summary>
/// Sets the volume level, in decibels, of the specified channel of the audio stream.
/// </summary>
/// <param name="channelNumber">The channel number.</param>
/// <param name="level">The new volume level in decibels.</param>
/// <param name="eventContext">A user context value that is passed to the notification callback.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int SetChannelVolumeLevel(
[In] [MarshalAs(UnmanagedType.U4)] UInt32 channelNumber,
[In] [MarshalAs(UnmanagedType.R4)] float level,
[In] [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);

/// <summary>
/// Sets the normalized, audio-tapered volume level of the specified channel in the audio stream.
/// </summary>
/// <param name="channelNumber">The channel number.</param>
/// <param name="level">The new master volume level expressed as a normalized value between 0.0 and 1.0.</param>
/// <param name="eventContext">A user context value that is passed to the notification callback.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int SetChannelVolumeLevelScalar(
[In] [MarshalAs(UnmanagedType.U4)] UInt32 channelNumber,
[In] [MarshalAs(UnmanagedType.R4)] float level,
[In] [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);

/// <summary>
/// Gets the volume level, in decibels, of the specified channel in the audio stream.
/// </summary>
/// <param name="channelNumber">The zero-based channel number.</param>
/// <param name="level">The volume level in decibels.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int GetChannelVolumeLevel(
[In] [MarshalAs(UnmanagedType.U4)] UInt32 channelNumber,
[Out] [MarshalAs(UnmanagedType.R4)] out float level);

/// <summary>
/// Gets the normalized, audio-tapered volume level of the specified channel of the audio stream.
/// </summary>
/// <param name="channelNumber">The zero-based channel number.</param>
/// <param name="level">The volume level expressed as a normalized value between 0.0 and 1.0.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int GetChannelVolumeLevelScalar(
[In] [MarshalAs(UnmanagedType.U4)] UInt32 channelNumber,
[Out] [MarshalAs(UnmanagedType.R4)] out float level);

/// <summary>
/// Sets the muting state of the audio stream.
/// </summary>
/// <param name="isMuted">True to mute the stream, or false to unmute the stream.</param>
/// <param name="eventContext">A user context value that is passed to the notification callback.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int SetMute(
[In] [MarshalAs(UnmanagedType.Bool)] Boolean isMuted,
[In] [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);

/// <summary>
/// Gets the muting state of the audio stream.
/// </summary>
/// <param name="isMuted">The muting state. True if the stream is muted, false otherwise.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int GetMute(
[Out] [MarshalAs(UnmanagedType.Bool)] out Boolean isMuted);

/// <summary>
/// Gets information about the current step in the volume range.
/// </summary>
/// <param name="step">The current zero-based step index.</param>
/// <param name="stepCount">The total number of steps in the volume range.</param>
/// <returns>An HRESULT code indicating whether the operation passed of failed.</returns>
[PreserveSig]
int GetVolumeStepInfo(
[Out] [MarshalAs(UnmanagedType.U4)] out UInt32 step,
[Out] [MarshalAs(UnmanagedType.U4)] out UInt32 stepCount);

}

#endregion
}

Usage:

Call GetMasterVolumeMute() method:

bool isMuted = AudioManager.GetMasterVolumeMute();

How can i control the volume of a specific software in the windows Volume Mixer?

According to the Internet, GetDisplayName() returning blank is OK. What you could do instead to get the actual information is to use IAudioSessionControl2 interface. Just cast your existing IAudioSessionControl ctl to it to obtain a reference:

IAudioSessionControl2 ctl2 = (IAudioSessionControl2)ctl;

After that you could use ctl2.GetProcessId() to obtain the PID and from that you could've used Process.GetProcessById(pid).MainModule.FileName to obtain the full exe filename.

Some pitfalls:

  1. Use ctl2.IsSystemSoundsSession() to check if current session is "System Sounds", since there is no process associated with such session and ctl2.GetProcessId() will fail on it.

  2. Be sure to compile your program targeting x64 if you are going to run in on an x64 OS. Otherwise you will get exception upon trying to get the exe names of other x64 processes.

  3. Several sessions could be associated with the same process, giving you duplicate results.

  4. You can then use FileVersionInfo.GetVersionInfo().FileDescription to get the description from the executable file's resources, if you want to show the UI similar to Windows mixer. To get the icon as well, you could use something like this: How can I get the icon from the executable file only having an instance of it's Process in C#

After that you could try to call SetApplicationVolume on the process you are interested in.

Mute system from code

I believe this is what you are looking for. this has been test with windows 7 and also this question as been asked on SO before. Which probably will help you get what you are looking for.



Related Topics



Leave a reply



Submit