At the moment I am trying to use a JSlider
in Java
to control the master volume of my PC. So far I have been able to locate my PC's main speaker's port. However, I do not know how to successfully call it and run a method like getValue() or setValue().
I have used the following code to search my PC for all of it's audio devices:
Mixer.Info [] mixers = AudioSystem.getMixerInfo();
System.out.println("There are " + mixers.length + " mixer info objects");
for (Mixer.Info mixerInfo : mixers)
{
System.out.println("mixer name: " + mixerInfo.getName());
Mixer mixer = AudioSystem.getMixer(mixerInfo);
Line.Info [] lineInfos = mixer.getTargetLineInfo(); // target, not source
for (Line.Info lineInfo : lineInfos)
{
System.out.println(" Line.Info: " + lineInfo);
Line line = null;
boolean opened = true;
try
{
line = mixer.getLine(lineInfo);
opened = line.isOpen() || line instanceof Clip;
if (!opened)
{
line.open();
}
FloatControl volCtrl = (FloatControl)line.getControl(FloatControl.Type.VOLUME);
System.out.println(" volCtrl.getValue() = " + volCtrl.getValue());
}
catch (LineUnavailableException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException iaEx)
{
System.out.println(" " + iaEx);
}
finally
{
if (line != null && !opened)
{
line.close();
}
}
}
}
How do I get control of my speakers line and alter the value?
I have used this website for help so far.
UPDATE
Okay so I think I've come a little bit closer. Under my test GUI program I'm trying to use the Java tutorial's code under "Getting a Line that Has the Desired Controls"(the link you gave me). I pasted it into my program under my JSlider's Change Listener.
This is what it looks like:
Port SPEAKER;
FloatControl volCtrl;
try {
Mixer mixer = AudioSystem.getMixer(null);
SPEAKER = (Port)mixer.getLine(Port.Info.SPEAKER);
SPEAKER.open();
volCtrl = (FloatControl) SPEAKER.getControl(
FloatControl.Type.VOLUME);
} catch (Exception e) {
System.out.println("Failed trying to find LINE_IN"
+ " VOLUME control: exception = " + e);
}
Whenever I move the slider it prints out the error Exception message "Failed trying to find...". Why isn't it letting me obtain the volCtrl on my main output speakers? How can I fix this code to get control of my SPEAKER?
Great find at JavaRanch! I've gotten a lot of valuable help there.
Once you locate your lines, this tutorial shows how to make a Control: http://docs.oracle.com/javase/tutorial/sound/controls.html
But sometimes the high and low vals are unexpected. I found one line that ranged from -80 to +6 (it was set to mimic a VU meter's decibel range). Thus, you may have to do some numerical conversions from the JSlider output to get a reasonable matching Control value, especially if the Control is exponential.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With