.net 如何以编程方式设置系统音量?

lskq00tm  于 2023-01-06  发布在  .NET
关注(0)|答案(7)|浏览(190)

如何使用C#应用程序更改Windows系统音量?

vu8f3i0k

vu8f3i0k1#

我有点晚了,但如果你现在正在寻找,有一个nuget包(AudioSwitcher.AudioApi.CoreAudio),简化音频交互。安装它,然后它是一样简单:

CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;
Debug.WriteLine("Current Volume:" + defaultPlaybackDevice.Volume);
defaultPlaybackDevice.Volume = 80;
ddhy6vgd

ddhy6vgd2#

下面是代码:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Test
{
    public class Test
    {
        private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
        private const int APPCOMMAND_VOLUME_UP = 0xA0000;
        private const int APPCOMMAND_VOLUME_DOWN = 0x90000;
        private const int WM_APPCOMMAND = 0x319;

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

        private void Mute()
        {
            SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
                (IntPtr)APPCOMMAND_VOLUME_MUTE);
        }

        private void VolDown()
        {
            SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
                (IntPtr)APPCOMMAND_VOLUME_DOWN);
        }

        private void VolUp()
        {
            SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
                (IntPtr)APPCOMMAND_VOLUME_UP);
        }
    }
}

dotnetcurry上找到
使用WPF时,您需要使用new WindowInteropHelper(this).Handle而不是this.Handle(感谢Alex Beals)

vjhs03f7

vjhs03f73#

如果其他答案中提供的教程过于复杂,您可以尝试使用keybd_event function进行类似的实现

[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
    • 用法:**
keybd_event((byte)Keys.VolumeUp, 0, 0, 0); // increase volume
keybd_event((byte)Keys.VolumeDown, 0, 0, 0); // decrease volume
bq3bfh9z

bq3bfh9z4#

如果您希望使用Core Audio API将其设置为精确值:

using CoreAudioApi;

public class SystemVolumeConfigurator
{
        private readonly MMDeviceEnumerator _deviceEnumerator = new MMDeviceEnumerator();
        private readonly MMDevice _playbackDevice;

        public SystemVolumeConfigurator()
        {
            _playbackDevice = _deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
        }

        public int GetVolume()
        {
            return (int)(_playbackDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
        }

        public void SetVolume(int volumeLevel)
        {
            if (volumeLevel < 0 || volumeLevel > 100)
                throw new ArgumentException("Volume must be between 0 and 100!");

            _playbackDevice.AudioEndpointVolume.MasterVolumeLevelScalar = volumeLevel / 100.0f;
        }
}
f1tvaqid

f1tvaqid5#

您可以将这个库https://gist.github.com/sverrirs/d099b34b7f72bb4fb386添加到您的项目中,并像这样更改音量;

VideoPlayerController.AudioManager.SetMasterVolume(100);

该库还包括用于更改应用程序音量、静音、获取当前音量级别等的选项。命名空间称为“视频播放器控制器”,但我在Windows窗体应用程序中使用它来更改系统音量,它工作正常,因此“视频”部分是任意的。

clj7thdc

clj7thdc6#

我的代码有点不同,但仍然使用CoreAudio
已下载pkg:nuget安装音频切换器。音频Api。核心音频-版本3.0.0.1

using AudioSwitcher.AudioApi.CoreAudio;
public partial class MainWindow : Window
{
public MainWindow()
{

InitializeComponent();

CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;

double vol = defaultPlaybackDevice.Volume;

defaultPlaybackDevice.Volume = defaultPlaybackDevice.Volume - 5.0;

defaultPlaybackDevice.Volume = defaultPlaybackDevice.Volume + 5.0;
}
}
7nbnzgx9

7nbnzgx97#

C#代码:

[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume
{
    int _0(); int _1(); int _2(); int _3();
    int SetMasterVolumeLevelScalar(float fLevel, Guid pguidEventContext);
    int _5();
    int GetMasterVolumeLevelScalar(out float pfLevel);
    int _7(); int _8(); int _9(); int _10(); int _11(); int _12();
}

[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice
{
    int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);
}

[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
    int _0();
    int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
}

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

public class Audio
{
    private static readonly IAudioEndpointVolume _MMVolume;

    static Audio()
    {
        var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
        enumerator.GetDefaultAudioEndpoint(0, 1, out IMMDevice dev);
        var aevGuid = typeof(IAudioEndpointVolume).GUID;
        dev.Activate(ref aevGuid, 1, 0, out _MMVolume);
    }

    public static int Volume
    {
        get
        {
            _MMVolume.GetMasterVolumeLevelScalar(out float level);
            return (int)(level * 100);
        }
        set
        {
            _MMVolume.SetMasterVolumeLevelScalar((float)value / 100, default);
        }
    }
}

用法:

Audio.Volume = 50;

有关MSDN的更多信息。

相关问题