views:

385

answers:

3

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  A: 

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++:

http://stackoverflow.com/questions/699603/change-volume-win32-c

Ravi Wallau
You can't do it in C# without P/Invoke...
EricSchaefer
The argumentation regarding console control is broken. There is nothing wrong with ANSI sequences except Windows doesn't support Them out of the box.
Thorbjørn Ravn Andersen
@Thorbjorn I understand that my example is not so good for this case.
Ravi Wallau
@EricSchafer But you could do it by using the Windows API from C# (using DllImport), right?
Ravi Wallau
or use jna and a dll (same as jni I guess)
rogerdpack
+1  A: 

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.

BalusC
A: 

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 !

Frank
wow that is intense :)
rogerdpack