问题
I am currently writing a test program in Java
that I want to be able to control my computer's main SPEAKER with a JSlider
on a GUI application. I have read through this page on the AudioSystem class and this page on Controls. It is my understanding that I need to get a Port or line through a mixer and then institute a Control on that line or port. Since I am controlling volume I need to implement a FloatControl
. My program compiles with no problem, however when I run it and adjust the JSlider I get sent the error message under the catch
clause.
This is my test program:
import java.awt.BorderLayout;
import java.io.IOException;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.Port;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class speakerWork2
{
public static void main(String [] args)throws IOException
{
Frame speaker = new Frame();
}
}
class Frame extends JFrame
{
JSlider mainVolume = new JSlider(JSlider.VERTICAL,0,100,50);
public Frame()
{
super();
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(100, 450);
setLocation(300,200);
add(mainVolume);
mainVolume.addChangeListener(new mainVolumeHandler());
}
public class mainVolumeHandler implements ChangeListener
{
int sliderVal = mainVolume.getValue();
public void setValue(FloatControl sliderVal)
{
}
public void stateChanged(ChangeEvent f)
{
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 SPEAKER"
+ " VOLUME control: exception = " + e);
}
}
}
}
When I run the above program, exception e prints:
java.lang.IllegalArgumentException: Line unsupported: SPEAKER target port
When I query my computer for mixers, lines and ports I get the following result for my Speakers...
mixer name: Port Speakers / Headphones (IDT High Definition Audio CODEC)
Line.Info: SPEAKER target port
volCtrl.getValue() = 1.0
What am I doing wrong, and what do I need to do to correct myself?
回答1:
I can think of two plausible issues to investigate:
(1) If your target speaker port appears on a specific mixer, you have to explicitly open that mixer if it is not the default mixer. You are currently opening the "default" mixer.
(2) If the audio resource is being used by another program, it may not be available. I've heard of this happening more with Linux than other systems.
来源:https://stackoverflow.com/questions/10840611/how-do-i-correctly-use-floatcontrol-with-the-java-sound-api