我的应用程序需要能够更改声音设备的系统音量级别。我正在使用C#和NAudio。我尝试在NAudio中使用CoreAudio Api,但这在Windows XP中不起作用,但我的程序需要支持XP。请帮助我,我需要使用什么,让我的程序支持XP以及最新的Windows。
答案 0 :(得分:2)
以下是使用P / Invoke调用的最简单且众所周知的方法:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace VolumeControl
{
public partial class Form1 : Form
{
[DllImport("winmm.dll")]
public static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);
[DllImport("winmm.dll")]
public static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);
public Form1()
{
InitializeComponent();
// By the default set the volume to 0
uint CurrVol = 0;
// At this point, CurrVol gets assigned the volume
waveOutGetVolume(IntPtr.Zero, out CurrVol);
// Calculate the volume
ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
// Get the volume on a scale of 1 to 10 (to fit the trackbar)
trackWave.Value = CalcVol / (ushort.MaxValue / 10);
}
private void trackWave_Scroll(object sender, EventArgs e)
{
// Calculate the volume that's being set
int NewVolume = ((ushort.MaxValue / 10) * trackWave.Value);
// Set the same volume for both the left and the right channels
uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
// Set the volume
waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
}
}
}
来源:http://www.geekpedia.com/tutorial176_Get-and-set-the-wave-sound-volume.html
此外,如果您希望将其与CoreAudioAPI结合使用 - 请阅读:Change master audio volume from XP to Windows 8 in C#
答案 1 :(得分:0)
在cmd中,我发现您可以运行javascript并从那里使用音量键。 我知道这可以在Windows 10的批处理文件中独立运行
您可以根据需要重复shl.SendKeys(String.fromCharCode(0xAF))
次,每次将音量提高10倍
@if (@a==@b) @end /*
:: batch portion
@ECHO OFF
cscript /e:jscript "%~f0"
:: JScript portion */
var shl = new ActiveXObject("WScript.Shell");
for (var i=0; i<5; i++) {
shl.SendKeys(String.fromCharCode(0xAF));
}