C#开发Windows应用程序中经常需要去控制系统的音量,分两种方式:
1.使用Win Api控制
2.使用C++ dll控制
Win Api控制:
使用user32.dll和winmm.dll都可以控制系统音量,区别是Win系统的版本。winmm.dll Xp环境下可用,user32.dll Vista及以上版本。
C++ dll控制:
CoreAudioApi 是C++ 第三方封装了音量控制,网上下载DLL后再项目中引用即可使用。CoreAudioApi Vista及以上版本支持。
下面给出代码
1.winmm控制方式,涉及Xp系统波形声音的左右声道,高位为左声道,低位为右声道:
winmm
[DllImport("winmm.dll", EntryPoint = "waveOutSetVolume")]
public static extern int WaveOutSetVolume(IntPtr hwo, uint dwVolume);
private void SetVol(double arg){
double newVolume = ushort.MaxValue * arg / 10.0;
uint v = ((uint)newVolume) & 0xffff;
uint vAll = v | (v << 16);
int retVal = WaveOutSetVolume(IntPtr.Zero, vAll);
}
2.user32控制方式:
user32
[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
public void SetVol(){
p = Process.GetCurrentProcess();
for (int i = 0; i < 5; i++) {
SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_UP);
}
}
private Process p;
private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
private const int APPCOMMAND_VOLUME_UP = 0x0a0000;
private const int APPCOMMAND_VOLUME_DOWN = 0x090000;
private const int WM_APPCOMMAND = 0x319;
3.CoreAudioApi
CoreAudioApi
Using CoreAudioApi;
public void SetVol(double arg) {
device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
device.AudioEndpointVolume.MasterVolumeLevelScalar = (float)arg;
}
private MMDevice device;
private MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();