using System;
using System.Data;
using System.Net;
using System.Net.Sockets;
using NAudio.CoreAudioApi;
namespace VolumeControlApp
{
class Program
{
private static int UDP_PORT = 8123;
private static UdpClient udpClient;
private static MMDeviceEnumerator deviceEnumerator = new MMDeviceEnumerator();
private static MMDevice defaultDevice;
static void Main(string[] args)
{
// 获取默认音频设备
defaultDevice = deviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
// 创建和启动UDP监听
udpClient = new UdpClient(UDP_PORT);
udpClient.BeginReceive(ReceiveCallback, null);
// 最小化到任务栏
SetWindowState();
Console.WriteLine("Volume Control App is running...");
Console.ReadLine();
// 关闭UDP监听并释放资源
udpClient.Close();
udpClient.Dispose();
}
private static void ReceiveCallback(IAsyncResult ar)
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, UDP_PORT);
byte[] receiveBytes = udpClient.EndReceive(ar, ref remoteEndPoint);
string command = System.Text.Encoding.UTF8.GetString(receiveBytes);
// 根据接收到的命令控制音量
if (command.Trim().ToLower() == "a")
{
AdjustVolumeBy(10);
}
else if (command.Trim().ToLower() == "d")
{
AdjustVolumeBy(-10);
}
// 继续监听
udpClient.BeginReceive(ReceiveCallback, null);
}
private static void AdjustVolumeBy(int increment)
{
// 获取当前音量
float currentVolume = defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar;
// 计算新的音量值
float newVolume = Math.Min(Math.Max(currentVolume + increment / 100f, 0f), 1f);
// 设置新的音量
defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar = newVolume;
Console.WriteLine("Volume adjusted. New volume: " + newVolume);
}
public static void SetWindowState()
{
var handle = NativeMethods.GetConsoleWindow();
if (handle != IntPtr.Zero)
{
NativeMethods.ShowWindow(handle, NativeMethods.SW_MINIMIZE);
}
}
private static class NativeMethods
{
public const int SW_MINIMIZE = 6;
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
}
}
}
需要引入NAudio包,VS中安装即可,a,d为命令,端口自己修改,默认音量步长为10