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
CoreAudioApiUsing 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();