How to adjust speaker volume from Java program?

放肆的年华 提交于 2019-12-12 09:19:02

问题


I'm running Win Vista, at the lower right side of the window there is a speaker icon next to the clock, I can click on it and adjust the volume, I wonder if there is a way in my Java program to do this automatically?

For instance, when my Java program starts, it turns the volume to 80, and when the program exits, it changes the volume back to the original level. I don't mind using Runtime.getRuntime().exec() if there is a way to achieve this effect.


回答1:


One of the main premises of Java is that an application written on it should work in any platform. That's why they dropped the support for environment variables in the Java 1.4 SDK but later re-enabled it. That's why there's no way to clean the Java console with a command like "cls", as it could work in some platforms but not in others.

That being said, you won't be able to do from Java. You can either create a JNI DLL in C++ or an application in C++ or in C# to do that.

More about doing this in C++:

change volume win32 c++




回答2:


Take a look in javax.sound API. Here's a tutorial about that, specifically here (in chapter Changing a Line's Volume) you can read how to set the volume. This knowledge should give enough Google keywords to find examples.




回答3:


I used the following code to simulate a volume adjustment :

Robot robot;             // Set speaker volume to 80
try
{
  robot=new Robot();
  robot.mouseMove(1828,1178);
  robot.mousePress(InputEvent.BUTTON1_MASK);
  robot.mouseRelease(InputEvent.BUTTON1_MASK);
  robot.delay(90);
  robot.mouseMove(1828,906);
  robot.mousePress(InputEvent.BUTTON1_MASK);
  robot.mouseRelease(InputEvent.BUTTON1_MASK);
  robot.delay(260);
  robot.mousePress(InputEvent.BUTTON1_MASK);
  robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
catch (AWTException ex)
{
  System.err.println("Can't start Robot: " + ex);
  System.exit(0);
}

And it worked !



来源:https://stackoverflow.com/questions/1734808/how-to-adjust-speaker-volume-from-java-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!