所需windows的控件
鏈接:https://pan.baidu.com/s/1oXMBlTisy-1wcr5tY4WNhQ
提取碼:09it
將音量控件放到所需控制的windows操作系統,c:\Windows\System32目錄下
::將音量控件放到相應目錄下
xcopy %cd%\msvcr120d.dll c:\Windows\System32\ /y /r /e
調用代碼如下
try { //單例模式 VolumeControl vc = VolumeControl.getInstance(); //設置音量值 vc.setMasterVolume(Integer.parseInt(volume)); log.warn("設置終端音量值為:" + volume+"成功!"); } catch (OperationFailedException e) { log.warn("設置終端音量值為:" + volume+"失敗!error:"+e); throw e; }
VolumeControl工具類代碼如下

1 package com.xianquan.common.volume; 2 3 /** 4 * 該類設計為單例模式 提供控制win7系統音量的方法 5 * 6 * @author lcoil 7 * 8 */ 9 public class VolumeControl { 10 11 static { 12 try{ 13 // add hook for release JNI resource on JVM shutdown 14 Runtime.getRuntime().addShutdownHook(new Thread (){ 15 @Override 16 public void run() { 17 try { 18 finalize(); 19 } catch (Throwable e) { 20 // TODO Auto-generated catch block 21 e.printStackTrace(); 22 } 23 release(); 24 }}); 25 26 System.loadLibrary("VolumeControlDLL"); 27 } catch(Exception e){ 28 System.out.println("=-=-=-=-=-="+e.getLocalizedMessage()+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); 29 } 30 } 31 32 private static VolumeControl uniqueInstance = null; 33 34 private VolumeControl() throws OperationFailedException { 35 init(); 36 } 37 38 /** 39 * 單例模式 40 * 41 * @return 唯一的VolumeControl 有可能為null 42 */ 43 public static VolumeControl getInstance() { 44 if (uniqueInstance == null) { 45 try { 46 uniqueInstance = new VolumeControl(); 47 } catch (OperationFailedException e) { 48 e.printStackTrace(); 49 return null; 50 } 51 } 52 return uniqueInstance; 53 } 54 55 /** 56 * cpp本地一些初始化 57 * 58 * @return 59 */ 60 private native void init() throws OperationFailedException; 61 62 /** 63 * 設置音量大小0~100 64 * 65 * @param num 66 * @return 操作是否成功 67 */ 68 public native void setMasterVolume(int num) throws OperationFailedException; 69 70 /** 71 * 72 * @return 當前音量大小1-100 73 */ 74 public native int getMasterVolume() throws OperationFailedException; 75 76 /** 77 * 設置是否靜音 true-是 false-否 78 * 79 * @param bMute 80 * @return 81 */ 82 public native void setMute(boolean bMute) throws OperationFailedException; 83 84 /** 85 * 得到當前靜音狀態 true-是 false-否 86 * 87 * @return 88 */ 89 public native boolean getMute() throws OperationFailedException; 90 91 /** 92 * cpp本地釋放指針等操作 93 * 94 * @return 95 */ 96 private native void finished(); 97 public native static void release(); 98 99 @Override 100 public void finalize() { 101 finished(); 102 try { 103 super.finalize(); 104 } catch (Throwable e) { 105 // TODO Auto-generated catch block 106 e.printStackTrace(); 107 } 108 } 109 110 }