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系统波形声音的左右声道,高位为左声道,低位为右声道:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 [DllImport("winmm.dll", EntryPoint = "waveOutSetVolume")] 2 public static extern int WaveOutSetVolume(IntPtr hwo, uint dwVolume); 3 4 private void SetVol(double arg){ 5 double newVolume = ushort.MaxValue * arg / 10.0; 6 7 uint v = ((uint)newVolume) & 0xffff; 8 uint vAll = v | (v << 16); 9 10 int retVal = WaveOutSetVolume(IntPtr.Zero, vAll); 11 }
2.user32控制方式:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 [DllImport("user32.dll")] 2 public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); 3 4 public void SetVol(){ 5 p = Process.GetCurrentProcess(); 6 for (int i = 0; i < 5; i++) { 7 SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_UP); 8 } 9 } 10 11 private Process p; 12 private const int APPCOMMAND_VOLUME_MUTE = 0x80000; 13 private const int APPCOMMAND_VOLUME_UP = 0x0a0000; 14 private const int APPCOMMAND_VOLUME_DOWN = 0x090000; 15 private const int WM_APPCOMMAND = 0x319;
3.CoreAudioApi
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 Using CoreAudioApi; 2 3 public void SetVol(double arg) { 4 device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia); 5 device.AudioEndpointVolume.MasterVolumeLevelScalar = (float)arg; 6 } 7 8 private MMDevice device; 9 private MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
参考:
1.Win Api winmm.dll http://msdn.microsoft.com/zh-cn/subscriptions/downloads/ms713762(v=vs.85).aspx
2.Win Api user32.dll http://www.cnblogs.com/ju2ender/archive/2010/12/21/1913025.html
3.CoreAudioApi http://www.codeproject.com/Articles/18520/Vista-Core-Audio-API-Master-Volume-Control