C# NAudio obtains and controls the system volume, can set the specified value and mute setting

I have been working on an alarm system recently, but the system volume is always muted by the security personnel. In desperation, I had to resort to this strategy and find a way to control the system volume. Before each call, I would first determine whether the sound was turned on, and then Go to the police again.

The way to get the volume is to use an open source tool NAudio, which can meet the functions of recording, playing recording, format conversion, mixing adjustment and so on. Here only introduces the acquisition and setting of the specified value of the system volume plus the mute switch; below is the code of each function, which is written in the form of a package, and can be called directly at the time. Setting the specified volume requires an int The value can be (0~100).

The first is to set the specified volume:

private void GetCurrentSpeakerVolume(int volume)
{
    var enumerator = new MMDeviceEnumerator();
    IEnumerable<MMDevice> speakDevices = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).ToArray();
    if (speakDevices.Count() > 0)
    {
        
        MMDevice mMDevice = speakDevices.ToList()[0];
        mMDevice.AudioEndpointVolume.MasterVolumeLevelScalar = volume / 100.0f;
    }
}

Get the current system volume value, the return value is an int value

private int GetCurrentSpeakerVolume()
{
    int volume = 0;
    var enumerator = new MMDeviceEnumerator();
 
    //获取音频输出设备
    IEnumerable<MMDevice> speakDevices = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).ToArray();
    if (speakDevices.Count() > 0)
    {
        MMDevice mMDevice = speakDevices.ToList()[0];
        volume = Convert.ToInt16(mMDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
    }
    return volume;
}

Set whether the system volume is muted, here is false to mute, true is to turn off mute

public void CancelTheMute()
{
     var enumerator = new MMDeviceEnumerator();
     IEnumerable<MMDevice> speakDevices = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).ToArray();
     MMDevice mMDevice = speakDevices.ToList()[0];
     mMDevice.AudioEndpointVolume.Mute = false;//系统音量静音
}

Because this is quoted from using, you only need to add a reference to use,

using NAudio;
using NAudio.Wave;
using VisioForge.Shared.NAudio;
using VisioForge.Shared.NAudio.CoreAudioApi;
using VisioForge.Shared.MediaFoundation;

If you have any questions, please comment or ask in private chat. I will reply to every question as much as possible.

Guess you like

Origin blog.csdn.net/weixin_37081112/article/details/113703284