gpt4 book ai didi

c# - 静音/取消静音,使用 C# 在 Windows 7 x64 中更改主音量

转载 作者:太空狗 更新时间:2023-10-29 20:02:08 25 4
gpt4 key购买 nike

如何使用 C# 在 Windows 7 中调整主音量?

我已经看到使用 winmm.dll 的出色实现 here , 但它适用于 XP 而不是 Windows 7。

最佳答案

我通过这段代码成功地使用了 nuget 包 Naudio:

public void SetVolume(int level)
{
try
{
//Instantiate an Enumerator to find audio devices
NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator();
//Get all the devices, no matter what condition or status
NAudio.CoreAudioApi.MMDeviceCollection DevCol = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.All);
//Loop through all devices
foreach (NAudio.CoreAudioApi.MMDevice dev in DevCol)
{
try
{
if (dev.State == NAudio.CoreAudioApi.DeviceState.Active)
{
var newVolume = (float)Math.Max(Math.Min(level, 100),0) / (float)100;

//Set at maximum volume
dev.AudioEndpointVolume.MasterVolumeLevelScalar = newVolume;

dev.AudioEndpointVolume.Mute = level == 0;

//Get its audio volume
_log.Info("Volume of " + dev.FriendlyName + " is " + dev.AudioEndpointVolume.MasterVolumeLevelScalar.ToString());
}
else
{
_log.Debug("Ignoring device " + dev.FriendlyName + " with state " + dev.State);
}
}
catch (Exception ex)
{
//Do something with exception when an audio endpoint could not be muted
_log.Warn(dev.FriendlyName + " could not be muted with error " + ex);
}
}
}
catch (Exception ex)
{
//When something happend that prevent us to iterate through the devices
_log.Warn("Could not enumerate devices due to an excepion: " + ex.Message);
}
}

关于c# - 静音/取消静音,使用 C# 在 Windows 7 x64 中更改主音量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2986007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com