Vma*_*man 67
我参加派对有点晚了,但如果你现在正在寻找一个可用的nuget包(AudioSwitcher.AudioApi.CoreAudio),它可以简化音频交互.安装它然后就像这样简单:
CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;
Debug.WriteLine("Current Volume:" + defaultPlaybackDevice.Volume);
defaultPlaybackDevice.Volume = 80;
Run Code Online (Sandbox Code Playgroud)
Pae*_*dow 49
这是代码:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
发现在dotnetcurry上
使用WPF时,您需要使用new WindowInteropHelper(this).Handle
而不是this.Handle
(感谢Alex Beals)
Cas*_*roy 14
如果其他答案中提供的教程过于复杂,您可以使用keybd_event函数尝试这样的实现
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
Run Code Online (Sandbox Code Playgroud)
用法:
keybd_event((byte)Keys.VolumeUp, 0, 0, 0); // increase volume
keybd_event((byte)Keys.VolumeDown, 0, 0, 0); // decrease volume
Run Code Online (Sandbox Code Playgroud)
egf*_*nor 12
如果您希望使用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;
}
}
Run Code Online (Sandbox Code Playgroud)