Java API sound

Discussion in 'Java' started by boutreau.adrien@gmail.com, Jan 8, 2007.

  1. Guest

    Hi

    I'm trying to use JAva sound API but I have an error on some computers
    with this code :

    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.BooleanControl;
    import javax.sound.sampled.FloatControl;
    import javax.sound.sampled.Line;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.Mixer;

    public class ControlTest {

    public static void main(String[] args) throws
    LineUnavailableException, InterruptedException {
    Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo();
    for (int i = 0; i < mixerInfos.length; i++) {

    System.out.println("AudioSystem info Name
    :"+mixerInfos.toString());
    Mixer mixer = AudioSystem.getMixer(mixerInfos);

    Line.Info[] targetLineInfos = mixer.getTargetLineInfo();
    System.out.println("target infos : " +
    targetLineInfos.length);
    for (int j = 0; j < targetLineInfos.length; j++) {
    setVolume(targetLineInfos[j]);
    }
    }
    }

    static boolean setVolume(Line.Info lineInfo) {
    try {
    System.out.println(lineInfo);
    Line line = AudioSystem.getLine(lineInfo);
    System.out.println("open " + line.getLineInfo());
    line.open();

    BooleanControl muteControl
    =(BooleanControl)line.getControl(BooleanControl.Type.MUTE);
    System.out.println("mute " + muteControl);
    muteControl.setValue(true);
    FloatControl control =
    (FloatControl)line.getControl(FloatControl.Type.VOLUME);
    control.setValue(control.getMinimum());
    System.out.println("val " + control.getValue());
    FloatControl controlp =
    (FloatControl)line.getControl(FloatControl.Type.MASTER_GAIN);
    controlp.setValue(control.getMinimum());
    System.out.println("val " + controlp.getValue());
    line.close();
    } catch (Exception e) {
    System.out.println(e);
    return false;
    }
    return true;
    }
    }


    Error :
    java.lang.IllegalArgumentException: Unsupported control type: Mute

    Is there a solution to control it ? Because I can control the Speaker
    Sound but not microphone...

    Thanks for your ideas
    Meric pour vos idees d avance =]
    , Jan 8, 2007
    #1
    1. Advertising

  2. wrote:
    ....
    > I'm trying to use JAva sound API but I have an error on some computers
    > with this code :

    ....
    > BooleanControl muteControl
    > =(BooleanControl)line.getControl(BooleanControl.Type.MUTE);
    > System.out.println("mute " + muteControl);
    > muteControl.setValue(true);
    > FloatControl control =
    > (FloatControl)line.getControl(FloatControl.Type.VOLUME);

    .....
    > Error :
    > java.lang.IllegalArgumentException: Unsupported control type: Mute
    >
    > Is there a solution to control it ? Because I can control the Speaker
    > Sound but not microphone...


    No mute, but a volume? Easy!

    Mute means 'go to 0 volume', so you might simply
    have a 'mute' button that when clicked, changes the
    volume to 0. Of course, you need to keep a recoord
    of the current volume for later 'unmute'.

    Andrew T.
    Andrew Thompson, Jan 8, 2007
    #2
    1. Advertising

  3. Guest

    This is same error for Volume
    java.lang.IllegalArgumentException: Unsupported control type: Volume

    Andrew Thompson a écrit :

    > wrote:
    > ...
    > > I'm trying to use JAva sound API but I have an error on some computers
    > > with this code :

    > ...
    > > BooleanControl muteControl
    > > =(BooleanControl)line.getControl(BooleanControl.Type.MUTE);
    > > System.out.println("mute " + muteControl);
    > > muteControl.setValue(true);
    > > FloatControl control =
    > > (FloatControl)line.getControl(FloatControl.Type.VOLUME);

    > ....
    > > Error :
    > > java.lang.IllegalArgumentException: Unsupported control type: Mute
    > >
    > > Is there a solution to control it ? Because I can control the Speaker
    > > Sound but not microphone...

    >
    > No mute, but a volume? Easy!
    >
    > Mute means 'go to 0 volume', so you might simply
    > have a 'mute' button that when clicked, changes the
    > volume to 0. Of course, you need to keep a recoord
    > of the current volume for later 'unmute'.
    >
    > Andrew T.
    , Jan 8, 2007
    #3
  4. Guest

    This is a very strange error because I can modify the volume of speaker
    but not for Recording control...

    a écrit :

    > This is same error for Volume
    > java.lang.IllegalArgumentException: Unsupported control type: Volume
    >
    > Andrew Thompson a écrit :
    >
    > > wrote:
    > > ...
    > > > I'm trying to use JAva sound API but I have an error on some computers
    > > > with this code :

    > > ...
    > > > BooleanControl muteControl
    > > > =(BooleanControl)line.getControl(BooleanControl.Type.MUTE);
    > > > System.out.println("mute " + muteControl);
    > > > muteControl.setValue(true);
    > > > FloatControl control =
    > > > (FloatControl)line.getControl(FloatControl.Type.VOLUME);

    > > ....
    > > > Error :
    > > > java.lang.IllegalArgumentException: Unsupported control type: Mute
    > > >
    > > > Is there a solution to control it ? Because I can control the Speaker
    > > > Sound but not microphone...

    > >
    > > No mute, but a volume? Easy!
    > >
    > > Mute means 'go to 0 volume', so you might simply
    > > have a 'mute' button that when clicked, changes the
    > > volume to 0. Of course, you need to keep a recoord
    > > of the current volume for later 'unmute'.
    > >
    > > Andrew T.
    , Jan 8, 2007
    #4
  5. wrote:
    > This is same error for Volume ..


    What is? Please refrain from top-posting.

    Andrew T.
    Andrew Thompson, Jan 8, 2007
    #5
  6. Guest

    Thanks for reading my post.

    So this is my code :

    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.FloatControl;
    import javax.sound.sampled.Line;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.Mixer;

    public class ControlTest {

    public static void main(String[] args) throws
    LineUnavailableException, InterruptedException {
    Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo();
    for (int i = 0; i < mixerInfos.length; i++) {
    Mixer mixer = AudioSystem.getMixer(mixerInfos);

    Line.Info[] targetLineInfos = mixer.getTargetLineInfo();
    for (int j = 0; j < targetLineInfos.length; j++) {
    setVolume(targetLineInfos[j]);
    }
    }
    }

    static boolean setVolume(Line.Info lineInfo) {
    try {
    Line line = AudioSystem.getLine(lineInfo);
    System.out.println(line.getLineInfo());
    line.open();
    FloatControl control =
    (FloatControl)line.getControl(FloatControl.Type.VOLUME);
    control.setValue(control.getMinimum());
    line.close();
    System.out.println("Volume : " + control.getValue());
    } catch (Exception e) {
    System.out.println(e);
    return false;
    }
    return true;
    }
    }

    I will modify sound for microphone and speaker. On my personal computer
    it works. But i'm trying on another computer with different driver and
    it modify only the speaker volume not microphone volume.

    I've got this error :
    interface TargetDataLine supporting 8 audio formats, and buffers of at
    least 32 bytes
    java.lang.IllegalArgumentException: Unsupported control type: Volume
    interface TargetDataLine supporting 8 audio formats, and buffers of at
    least 32 bytes
    java.lang.IllegalArgumentException: Unsupported control type: Volume
    SPEAKER target port
    Volume : 0.0
    Any ideas ?

    Andrew Thompson a écrit :

    > wrote:
    > > This is same error for Volume ..

    >
    > What is? Please refrain from top-posting.
    >
    > Andrew T.
    , Jan 8, 2007
    #6
  7. wrote:
    > Andrew Thompson a écrit :


    > Thanks for reading my post.


    What post?

    > Any ideas ?


    > > ...Please refrain from top-posting.


    Andrew T.
    Andrew Thompson, Jan 8, 2007
    #7
  8. Guest

    I don't understand what are you requesting. Sorry for my poor english
    =[


    Andrew Thompson a écrit :

    > wrote:
    > > Andrew Thompson a écrit :

    >
    > > Thanks for reading my post.

    >
    > What post?
    >
    > > Any ideas ?

    >
    > > > ...Please refrain from top-posting.

    >
    > Andrew T.
    , Jan 8, 2007
    #8
  9. wrote:
    > I don't understand what are you requesting.


    Google is your friend.
    <http://www.google.com/search?q=top-post>

    Andrew T.
    Andrew Thompson, Jan 8, 2007
    #9
  10. Andrew Thompson wrote:
    > wrote:
    > > I don't understand what are you requesting.

    >
    > Google is your friend.
    > <http://www.google.com/search?q=top-post>


    And since it came up, please note the 'quote'.
    <http://groups.google.com/groups/profile?enc_user=7mTjyhYAAADCSWBnolz9mAH1YeBMyEJTo4cocwWvDVg2RHsu8f1bCg>

    ( ..if any of it is worth reading, put it here -
    I did not read the email. )

    Andrew T.
    Andrew Thompson, Jan 8, 2007
    #10
  11. Oliver Wong Guest

    <> wrote in message
    news:...
    > Hi
    >
    > I'm trying to use JAva sound API but I have an error on some computers
    > with this code :
    >
    > import javax.sound.sampled.AudioSystem;
    > import javax.sound.sampled.BooleanControl;
    > import javax.sound.sampled.FloatControl;
    > import javax.sound.sampled.Line;
    > import javax.sound.sampled.LineUnavailableException;
    > import javax.sound.sampled.Mixer;
    >
    > public class ControlTest {
    >
    > public static void main(String[] args) throws
    > LineUnavailableException, InterruptedException {
    > Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo();
    > for (int i = 0; i < mixerInfos.length; i++) {
    >
    > System.out.println("AudioSystem info Name
    > :"+mixerInfos.toString());
    > Mixer mixer = AudioSystem.getMixer(mixerInfos);
    >
    > Line.Info[] targetLineInfos = mixer.getTargetLineInfo();
    > System.out.println("target infos : " +
    > targetLineInfos.length);
    > for (int j = 0; j < targetLineInfos.length; j++) {
    > setVolume(targetLineInfos[j]);
    > }
    > }
    > }
    >
    > static boolean setVolume(Line.Info lineInfo) {
    > try {
    > System.out.println(lineInfo);
    > Line line = AudioSystem.getLine(lineInfo);
    > System.out.println("open " + line.getLineInfo());
    > line.open();
    >
    > BooleanControl muteControl
    > =(BooleanControl)line.getControl(BooleanControl.Type.MUTE);
    > System.out.println("mute " + muteControl);
    > muteControl.setValue(true);
    > FloatControl control =
    > (FloatControl)line.getControl(FloatControl.Type.VOLUME);
    > control.setValue(control.getMinimum());
    > System.out.println("val " + control.getValue());
    > FloatControl controlp =
    > (FloatControl)line.getControl(FloatControl.Type.MASTER_GAIN);
    > controlp.setValue(control.getMinimum());
    > System.out.println("val " + controlp.getValue());
    > line.close();
    > } catch (Exception e) {
    > System.out.println(e);
    > return false;
    > }
    > return true;
    > }
    > }
    >
    >
    > Error :
    > java.lang.IllegalArgumentException: Unsupported control type: Mute


    Can you tell us which line is throwing this exception?

    - Oliver
    Oliver Wong, Jan 8, 2007
    #11
  12. Guest


    > > (FloatControl)line.getControl(FloatControl.Type.VOLUME);
    > > control.setValue(control.getMinimum());

    this one
    , Jan 11, 2007
    #12
  13. Oliver Wong Guest

    <> wrote in message
    news:...
    > Hi
    >
    > I'm trying to use JAva sound API but I have an error on some computers
    > with this code :

    [code snipped]
    >
    >
    > Error :
    > java.lang.IllegalArgumentException: Unsupported control type: Mute
    >
    > Is there a solution to control it ? Because I can control the Speaker
    > Sound but not microphone...


    It looks basically like certain lines don't support some of the controls
    you want. I've modified your code as follows:

    <SSCCE>

    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.BooleanControl;
    import javax.sound.sampled.FloatControl;
    import javax.sound.sampled.Line;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.Mixer;

    public class ControlTest {

    public static void main(String[] args) throws LineUnavailableException,
    InterruptedException {
    Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo();
    for (int i = 0; i < mixerInfos.length; i++) {

    System.out.println("AudioSystem info Name:" + mixerInfos.toString());
    Mixer mixer = AudioSystem.getMixer(mixerInfos);

    Line.Info[] targetLineInfos = mixer.getTargetLineInfo();
    System.out.println("target infos : " + targetLineInfos.length);
    for (int j = 0; j < targetLineInfos.length; j++) {
    try {
    setVolume(targetLineInfos[j]);
    }
    catch (IllegalArgumentException e) {
    continue;
    }
    }
    }
    }

    static void setVolume(Line.Info lineInfo) throws LineUnavailableException {
    System.out.println(lineInfo);
    Line line = AudioSystem.getLine(lineInfo);
    System.out.println(" open " + line.getLineInfo());
    line.open();
    line.getControls(); /*SPECIAL LINE*/
    BooleanControl muteControl =
    (BooleanControl)line.getControl(BooleanControl.Type.MUTE);
    System.out.println(" mute " + muteControl);
    muteControl.setValue(true);
    FloatControl control =
    (FloatControl)line.getControl(FloatControl.Type.VOLUME);
    control.setValue(control.getMinimum());
    System.out.println(" val " + control.getValue());
    FloatControl controlp =
    (FloatControl)line.getControl(FloatControl.Type.MASTER_GAIN);
    controlp.setValue(control.getMinimum());
    System.out.println(" val " + controlp.getValue());
    line.close();
    }
    }
    </SSCCE>

    Notice the line marked /*SPECIAL LINE*/. If you set a breakpoint there, you
    can look at the return value of line.getControls() to see what controls a
    particular line supports.

    - Oliver
    Oliver Wong, Jan 11, 2007
    #13
  14. Guest

    With using your code I get this :

    AudioSystem info Name:primary Sound Driver, version Unknown Version
    target infos : 0
    AudioSystem info Name:Realtek HD Audio output, version Unknown Version
    target infos : 0
    AudioSystem info Name:primary Sound Capture Driver, version Unknown
    Version
    target infos : 1
    interface TargetDataLine supporting 8 audio formats, and buffers of at
    least 32 bytes
    open interface TargetDataLine supporting 8 audio formats, and buffers
    of at least 32 bytes
    AudioSystem info Name:Realtek HD Audio Input, version Unknown Version
    target infos : 1
    interface TargetDataLine supporting 8 audio formats, and buffers of at
    least 32 bytes
    open interface TargetDataLine supporting 8 audio formats, and buffers
    of at least 32 bytes
    AudioSystem info Name:Java Sound Audio Engine, version 1.0
    target infos : 0
    AudioSystem info Name:port Realtek HD Audio output, version 5.10
    target infos : 1
    SPEAKER target port
    open SPEAKER target port
    mute Mute Control with current value: false
    val 0.0
    AudioSystem info Name:port Realtek HD Audio Input, version 5.10
    target infos : 0

    This is very strange : volume are mute and set to minimum, but volume
    (not play back) of my microphone doesn't change. I need to modify
    micrphone volume =[
    , Jan 12, 2007
    #14
  15. Oliver Wong Guest

    <> wrote in message
    news:...
    > With using your code I get this :
    >
    > AudioSystem info Name:primary Sound Driver, version Unknown Version
    > target infos : 0
    > AudioSystem info Name:Realtek HD Audio output, version Unknown Version
    > target infos : 0
    > AudioSystem info Name:primary Sound Capture Driver, version Unknown
    > Version
    > target infos : 1
    > interface TargetDataLine supporting 8 audio formats, and buffers of at
    > least 32 bytes
    > open interface TargetDataLine supporting 8 audio formats, and buffers
    > of at least 32 bytes
    > AudioSystem info Name:Realtek HD Audio Input, version Unknown Version
    > target infos : 1
    > interface TargetDataLine supporting 8 audio formats, and buffers of at
    > least 32 bytes
    > open interface TargetDataLine supporting 8 audio formats, and buffers
    > of at least 32 bytes
    > AudioSystem info Name:Java Sound Audio Engine, version 1.0
    > target infos : 0
    > AudioSystem info Name:port Realtek HD Audio output, version 5.10
    > target infos : 1
    > SPEAKER target port
    > open SPEAKER target port
    > mute Mute Control with current value: false
    > val 0.0
    > AudioSystem info Name:port Realtek HD Audio Input, version 5.10
    > target infos : 0
    >
    > This is very strange : volume are mute and set to minimum, but volume
    > (not play back) of my microphone doesn't change. I need to modify
    > micrphone volume =[


    For my particular soundcard, the recording line has zero controls. If
    your program is going to work on my computer, it has to take into account
    that it cannot use controls to mute or adjust the volume of the recording
    line.

    Perhaps you could just record as-is, and then "mute" in software? I.e.
    take whatever waveform you receive, and multiply it with 0.

    - Oliver
    Oliver Wong, Jan 12, 2007
    #15
  16. Guest

    I was using mixer but port is better solution ;

    Solution trouvee :
    (dessine dans un jpanel les configuration du micros)

    //jpanel.java
    package Voice.Commander.Sounds.Settings;


    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;

    import javax.sound.sampled.FloatControl;
    import javax.sound.sampled.Port;
    import javax.swing.BoxLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JLabel;
    import javax.swing.JProgressBar;
    import javax.swing.JSlider;
    import javax.swing.WindowConstants;
    import javax.swing.JFrame;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;

    import Voice.Commander.Main.Class.VCMainClass;




    public class AudioDraw extends javax.swing.JPanel implements
    ActionListener, ItemListener,
    ChangeListener, PropertyChangeListener{

    /**
    *
    */
    private static final long serialVersionUID = 1L;
    /**
    * Auto-generated main method to display this
    * JPanel inside a new JFrame.
    */


    private JLabel jLabelVolume;
    private JLabel jLabelMicrophone;

    private JComboBox[] mixerSelector = new JComboBox[2];
    private JProgressBar[] volumeMeter = new JProgressBar[2];
    private JComboBox[] volumePort = new JComboBox[2];
    private JCheckBox[] muteButton = new JCheckBox[2];
    private JLabel Outputimage;
    private JLabel inputimage;
    private JSlider[] volumeSlider = new JSlider[2];
    private AudioSettings m_audioSettings;


    public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new AudioDraw());
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    }

    public AudioDraw() {
    super();
    this.setOpaque(false);
    m_audioSettings = new AudioSettings();

    CreateInterface(0); //micro
    CreateInterface(1); //olvume
    initGUI();
    }

    private void initGUI() {
    try {
    FlowLayout thisLayout = new FlowLayout();
    this.setLayout(thisLayout);
    this.setPreferredSize(new java.awt.Dimension(365, 100));
    this.setSize(365, 100);
    this.setLayout(null);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    private void CreateInterface(int d)
    {
    if (d == 1)
    {
    jLabelVolume = new JLabel();
    this.add(jLabelVolume);
    jLabelVolume.setText(VCMainClass.myLang.MicPlayback);
    jLabelVolume.setBounds(270, 0, 77, 14);
    }
    else
    {
    jLabelMicrophone = new JLabel();
    this.add(jLabelMicrophone);
    jLabelMicrophone.setText(VCMainClass.myLang.MicRecord);
    jLabelMicrophone.setBounds(45, 0, 70, 14);
    }
    {
    inputimage = new JLabel(new ImageIcon("Data/VC/Mic 24x24.png"));
    this.add(inputimage);
    inputimage.setBounds(45, 20, 24, 24);
    }
    {
    Outputimage = new JLabel(new ImageIcon("Data/VC/Sounds 24x24.png"));
    this.add(Outputimage);
    Outputimage.setBounds(274, 20, 24, 24);
    }


    volumePort[d] = new JComboBox(m_audioSettings.getPorts(d).toArray());
    volumePort[d].addItemListener(this);
    if (d == 0)
    volumePort[d].setBounds(7, 50, 110, 21);
    else
    volumePort[d].setBounds(232, 50, 110, 21);
    this.add(volumePort[d]);

    volumeSlider[d] = new JSlider(0, 100, 100);
    volumeSlider[d].setOrientation(volumeSlider[d].VERTICAL);
    volumeSlider[d].addChangeListener(this);

    volumeSlider[d].setOpaque(false);

    if (d == 0)
    volumeSlider[d].setBounds(135, 0, 28, 77);
    else
    volumeSlider[d].setBounds(183, 0, 28, 77);

    this.add(volumeSlider[d]);

    m_audioSettings.setSelPort(d, 0);
    initNewPort(d);
    }
    private void updateVolume(int d) {
    FloatControl c = m_audioSettings.getSelVolControl(d);
    if (c != null && volumeSlider[d].isEnabled()) {

    float newVol = ((volumeSlider[d].getValue() / 100.0f)
    * (c.getMaximum() - c.getMinimum())) + c.getMinimum();
    c.setValue(newVol);
    }
    }
    private void initNewPort(int d) {
    Port port = m_audioSettings.getSelPort(d);
    FloatControl c = m_audioSettings.getSelVolControl(d);
    volumeSlider[d].setEnabled(port != null && c != null);
    updateVolumeSlider(d);
    }


    private void updateVolumeSlider(int d) {
    FloatControl c = m_audioSettings.getSelVolControl(d);
    if (c != null && volumeSlider[d].isEnabled()) {
    int newPos = (int) (((c.getValue() - c.getMinimum())
    / (c.getMaximum() - c.getMinimum())) * 100.0f);
    if (newPos != volumeSlider[d].getValue()) {
    volumeSlider[d].setValue(newPos);
    }
    }
    }
    public void actionPerformed(ActionEvent e) {
    }

    public void itemStateChanged(ItemEvent e) {
    int d = -1;
    if (e.getSource() == volumePort[0]) {
    d = 0;
    } else if (e.getSource() == volumePort[1]) {
    d = 1;
    }
    if ((d >= 0) && (e.getStateChange() == ItemEvent.SELECTED)) {
    m_audioSettings.setSelPort(d, volumePort[d].getSelectedIndex());
    initNewPort(d);
    return;
    }
    d = -1;
    if (e.getSource() == mixerSelector[0]) {
    d = 0;
    } else if (e.getSource() == mixerSelector[1]) {
    d = 1;
    }
    if ((d >= 0) && (e.getStateChange() == ItemEvent.SELECTED)) {
    m_audioSettings.setSelMixer(d, mixerSelector[d].getSelectedIndex());
    return;
    }
    d = -1;

    d = -1;
    if (e.getSource() == muteButton[0]) {
    d = 0;
    } else if (e.getSource() == muteButton[1]) {
    d = 1;
    }
    }

    public void stateChanged(ChangeEvent e) {
    int d;
    if (e.getSource() == volumeSlider[0]) {
    d = 0;
    } else if (e.getSource() == volumeSlider[1]) {
    d = 1;
    } else {
    return;
    }
    updateVolume(d);
    }

    public void propertyChange(PropertyChangeEvent evt) {
    }
    }

    //audiobase.java
    package Voice.Commander.Sounds.Settings;

    import java.io.*;
    import javax.sound.sampled.*;

    import static Voice.Commander.Sounds.Settings.Constants.*;

    // base class for stream-based audio i/o
    public abstract class AudioBase implements LineListener {

    protected AudioFormat lineFormat;
    protected AudioFormat netFormat;
    protected int formatCode = -1; // force initialization

    protected int bufferSizeMillis;
    protected int bufferSize;
    protected Mixer mixer;
    protected String title;
    protected DataLine line;

    // current volume level: 0..128, or -1 for (none)
    protected int lastLevel = -1;
    protected boolean muted = false;

    protected AudioBase(String title, int formatCode, Mixer mixer, int
    bufferSizeMillis) {
    this.title = title;
    this.bufferSizeMillis = bufferSizeMillis;
    this.mixer = mixer;
    try {
    setFormatCode(formatCode);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public void update(LineEvent event) {
    if (DEBUG) {
    if (event.getType().equals(LineEvent.Type.STOP)) {
    out(title+": Stop");
    } else if (event.getType().equals(LineEvent.Type.START)) {
    out(title+": Start");
    } else if (event.getType().equals(LineEvent.Type.OPEN)) {
    out(title+": Open");
    } else if (event.getType().equals(LineEvent.Type.CLOSE)) {
    out(title+": Close");
    }
    }
    }

    // opens the sound hardware
    public void open() throws Exception {
    closeLine(false);
    destroyLine();
    createLine();
    openLine();
    }

    protected abstract void createLineImpl() throws Exception;

    private void createLine() throws Exception {
    try {
    line = null;
    createLineImpl();
    line.addLineListener(this);
    if (DEBUG) {
    out("Got line for "+title+": "+line.getClass());
    }
    } catch (LineUnavailableException ex) {
    throw new Exception("Unable to open "+title+": "+ex.getMessage());
    }
    }

    protected abstract void openLineImpl() throws Exception;

    private void openLine() throws Exception {
    try {
    // align to frame size
    bufferSize = (int) AudioUtils.millis2bytes(bufferSizeMillis,
    lineFormat);
    bufferSize -= bufferSize % lineFormat.getFrameSize();
    openLineImpl();
    if (DEBUG) out(title+": opened line");
    bufferSize = line.getBufferSize();
    if (VERBOSE) {
    out(title+": buffersize="+bufferSize+" bytes.");
    }
    } catch (LineUnavailableException ex) {
    throw new Exception("Unable to open "+title+": "+ex.getMessage());
    }
    }

    public void start() throws Exception {
    if (line == null) {
    if (DEBUG) out(title+": Call to start(), but line not created!");
    throw new Exception(title+": cannot start");
    }
    line.flush();
    line.start();
    if (DEBUG) out(title+": started line");
    }

    public void close() {
    close(false);
    }

    public void close(boolean willReopen) {
    closeLine(willReopen);
    destroyLine();
    }

    protected void closeLine(boolean willReopen) {
    if (!willReopen) lastLevel = -1;
    if (line!=null) {
    line.flush();
    line.stop();
    line.close();
    if (DEBUG && title!=null) out(title+": line closed.");
    }
    }

    private void destroyLine() {
    if (line != null) {
    line.removeLineListener(this);
    }
    line = null;
    }

    public boolean isStarted() {
    return (line != null) && (line.isActive());
    }

    public boolean isOpen() {
    return (line != null) && (line.isOpen());
    }

    public int getBufferSize() {
    return bufferSize;
    }

    public int getBufferSizeMillis() {
    return bufferSizeMillis;
    }

    public void setBufferSizeMillis(int bufferSizeMillis) throws
    Exception {
    if (this.bufferSizeMillis == bufferSizeMillis) return;
    boolean wasOpen = isOpen();
    boolean wasStarted = isStarted();
    closeLine(true);

    this.bufferSizeMillis = bufferSizeMillis;

    if (wasOpen) {
    openLine();
    if (wasStarted) {
    start();
    }
    }
    }

    public int getFormatCode() {
    return formatCode;
    }

    public void setFormatCode(int formatCode) throws Exception {
    if (this.formatCode == formatCode) return;
    boolean wasOpen = isOpen();
    if (wasOpen) {
    throw new Exception("cannot change format while open");
    }
    this.lineFormat = AudioUtils.getLineAudioFormat(formatCode);
    this.netFormat = AudioUtils.getNetAudioFormat(formatCode);
    }

    public void setMixer(Mixer mixer) throws Exception {
    if (this.mixer == mixer) return;
    boolean wasOpen = isOpen();
    boolean wasStarted = isStarted();
    close(true);

    this.mixer = mixer;

    if (wasOpen) {
    createLine();
    openLine();
    if (wasStarted) {
    start();
    }
    }
    }

    public void setMuted(boolean muted) {
    this.muted = muted;
    }

    public boolean isMuted() {
    return this.muted;
    }

    public int getLevel() {
    return lastLevel;
    }

    // find the current playback level: the maximum value of this
    buffer
    protected void calcCurrVol(byte[] b, int off, int len) {
    int end = off+len;
    int sampleSize = (lineFormat.getSampleSizeInBits() + 7) / 8;
    int max = 0;
    if (sampleSize == 1) {
    // 8-bit
    for ( ; off < end; off++) {
    int sample = (byte) (b[off] + 128);
    if (sample < 0) sample = -sample;
    if (sample > max) max = sample;
    }
    lastLevel = max;
    } else if (sampleSize == 2) {
    if (lineFormat.isBigEndian()) {
    // 16-bit big endian
    for ( ; off < end; off+=2) {
    int sample = (short) ((b[off]<<8) | (b[off+1] & 0xFF));
    if (sample < 0) sample = -sample;
    if (sample > max) max = sample;
    }
    } else {
    // 16-bit little endian
    for ( ; off < end; off+=2) {
    int sample = (short) ((b[off+1]<<8) | (b[off] & 0xFF));
    if (sample < 0) sample = -sample;
    if (sample > max) max = sample;
    }
    }
    //System.out.print("max="+max+" ");
    lastLevel = max >> 8;
    //System.out.print(":"+len+":");
    //System.out.print("[lL="+lastLevel+"
    "+getClass().toString()+"]");
    } else {
    lastLevel = -1;
    }
    }

    // find the current playback level: the maximum value of this
    buffer
    protected void muteBuffer(byte[] b, int off, int len) {
    int end = off+len;
    int sampleSize = (lineFormat.getSampleSizeInBits() + 7) / 8;
    byte filler = 0;
    if (sampleSize == 1) {
    filler = -128;
    }
    for ( ; off < end; off++) {
    b[off] = filler;
    }
    }

    }

    //audiosettings :
    package Voice.Commander.Sounds.Settings;


    import java.util.ArrayList;
    import java.util.List;

    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.BooleanControl;
    import javax.sound.sampled.CompoundControl;
    import javax.sound.sampled.Control;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.FloatControl;
    import javax.sound.sampled.Line;
    import javax.sound.sampled.Mixer;
    import javax.sound.sampled.Port;

    import static Voice.Commander.Sounds.Settings.Constants.*;

    class AudioSettings {

    /** the selected port */
    private Port[] port = new Port[2];
    /** the selected control for port volume */
    private FloatControl[] portVolume = new FloatControl[2];
    /** the selected control for port select (only for Source Ports) */
    private BooleanControl[] portSelect = new BooleanControl[2];

    /** all compound controls available on the system, as a display
    list */
    private List<String> portNames[] = new List[2]; // $$ generics

    /** all Ports available on the system (maybe the same ones) */
    private List<Port>[] ports = new List[2];

    /** the index of the controls array for the respective compound
    control */
    private List<Integer>[] controlIndex = new List[2];

    /** the selected mixer. If null, use default */
    private Mixer[] mixer = new Mixer[2];

    /** all mixers */
    private List<Mixer>[] mixers = new List[2];

    /** index in BUFFER_SIZE_MILLIS */
    private int[] bufferSizeIndex = new int[2];

    private boolean inited = false;


    public AudioSettings () {
    portNames[0] = new ArrayList<String>();
    portNames[1] = new ArrayList<String>();
    ports[0] = new ArrayList<Port>();
    ports[1] = new ArrayList<Port>();
    controlIndex[0] = new ArrayList<Integer>();
    controlIndex[1] = new ArrayList<Integer>();
    mixers[0] = new ArrayList<Mixer>();
    mixers[1] = new ArrayList<Mixer>();
    bufferSizeIndex[0] = BUFFER_SIZE_INDEX_DEFAULT;
    bufferSizeIndex[1] = BUFFER_SIZE_INDEX_DEFAULT;
    }

    public void init() {
    for (int d = 0; d < 2; d++) {
    portNames[d].clear();
    ports[d].clear();
    controlIndex[d].clear();
    mixers[d].clear();
    }
    // go through all mixer and fill all lists
    Mixer.Info[] infos = AudioSystem.getMixerInfo();
    for (int i = 0; i < infos.length; i++) {
    try {
    Mixer mixer = AudioSystem.getMixer(infos);
    addMixer(mixer, mixer.getSourceLineInfo(), DIR_SPK);
    addMixer(mixer, mixer.getTargetLineInfo(), DIR_MIC);
    } catch (Exception e) {
    if (DEBUG) e.printStackTrace();
    }
    }
    // add defaults, if multiples exist
    for (int d = 0; d < 2; d++) {
    if (mixers[d].size() > 1) {
    mixers[d].add(0, null);
    }
    }
    inited = true;
    if (VERBOSE) {
    out("Microphone Ports: "+ports[DIR_MIC].size());
    out("Microphone Mixers: "+mixers[DIR_MIC].size());
    out("Speaker Ports: "+ports[DIR_SPK].size());
    out("Speaker Mixers: "+mixers[DIR_SPK].size());
    }
    }

    public void exit() {
    for (int d = 0; d < 2; d++) {
    closePort(d);
    portNames[d].clear();
    controlIndex[d].clear();
    ports[d].clear();
    mixers[d].clear();
    }
    }

    private void addMixer(Mixer mixer, Line.Info[] infos, int
    dirDataLine) {

    for (int i = 0; i<infos.length; i++) {
    try {
    if (infos instanceof Port.Info) {
    Port.Info info = (Port.Info) infos;
    int d;
    if (info.isSource()) {
    // microphone port
    d = DIR_MIC;
    } else {
    d = DIR_SPK;
    }
    // walk through all top-level controls
    Port p = (Port) mixer.getLine(info);
    p.open();
    try {
    Control[] cs = p.getControls();
    for (int c = 0 ; c < cs.length; c++) {
    if (cs[c] instanceof CompoundControl) {
    ports[d].add(p);
    portNames[d].add(cs[c].getType().toString());
    // $$ autoboxing
    controlIndex[d].add(c);
    }
    }
    } finally {
    p.close();
    }
    }
    if (infos instanceof DataLine.Info) {
    if (!mixers[dirDataLine].contains(mixer)) {
    mixers[dirDataLine].add(mixer);
    }
    }
    } catch (Exception e) {
    if (DEBUG) e.printStackTrace();
    }
    }
    }

    // MIXER HANDLING //

    public List<String> getMixers(int d) {
    if (!inited) init();
    List<String> res = new ArrayList<String>();
    for (Mixer m : mixers[d]) { // $$ enhanced for
    if (m == null) {
    res.add("(Default)");
    } else {
    res.add(m.getMixerInfo().getName());
    }
    }
    return res;
    }

    public Mixer getSelMixer(int d) {
    return mixer[d];
    }

    /** set index in list returned in getMixers */
    public void setSelMixer(int d, int index) {
    if (index < 0 || index >= mixers[d].size()) {
    if (DEBUG) out("setSelMixer out of range: iondex="+index);
    return;
    } else {
    mixer[d] = mixers[d].get(index);
    }
    }



    // PORT HANDLING //

    public List<String> getPorts(int d) {
    if (!inited) init();
    return portNames[d];
    }


    public Port getSelPort(int d) {
    return port[d];
    }

    public FloatControl getSelVolControl(int d) {
    return portVolume[d];
    }

    /** set index in list returned in getMixers */
    public void setSelPort(int d, int index) {
    setSelPort(d, index, true);
    }

    public void setSelPort(int d, int index, boolean doSelect) {
    if (index < 0 || index >= ports[d].size()) {
    if (DEBUG) out("setSelPort out of range: iondex="+index);
    closePort(d);
    return;
    } else {
    setupPort(d, ports[d].get(index), controlIndex[d].get(index)); //
    $$ autoboxing
    if (doSelect && d == DIR_MIC && portSelect[d] != null) {
    portSelect[d].setValue(true);
    }
    if (DEBUG) out("Selected "+portNames[d].get(index));
    }
    }

    private void closePort(int d) {
    if (port[d] != null) {
    port[d].close();
    port[d] = null;
    }
    portVolume[d] = null;
    portSelect[d] = null;
    }

    private void setupPort(int d, Port p, int controlIndex) {
    if (p != port[d] && port[d] != null) {
    port[d].close();
    }
    portVolume[d] = null;
    portSelect[d] = null;
    port[d] = p;
    try {
    p.open();
    Control[] cs = p.getControls();
    if (controlIndex >= cs.length) {
    throw new Exception("control not found!");
    }
    if (!(cs[controlIndex] instanceof CompoundControl)) {
    throw new Exception("control not found!");
    }
    CompoundControl cc = (CompoundControl) cs[controlIndex];
    cs = cc.getMemberControls();
    // find VolumeControl and select
    for (Control c : cs) { // $$ enhanced for
    if ((c instanceof FloatControl)
    && c.getType().equals(FloatControl.Type.VOLUME)
    && (portVolume[d] == null)) {
    portVolume[d] = (FloatControl) c;
    }
    if ((c instanceof BooleanControl)
    && c.getType().toString().contains("elect")
    && (portSelect[d] == null)) {
    portSelect[d] = (BooleanControl) c;
    }
    }

    } catch (Exception e) {
    if (DEBUG) e.printStackTrace();
    closePort(d);
    }
    }

    // buffer size //

    public int getBufferSizeMillis(int d) {
    return BUFFER_SIZE_MILLIS[bufferSizeIndex[d]];
    }

    public int getBufferSizeIndex(int d) {
    return bufferSizeIndex[d];
    }

    public void setBufferSizeIndex(int d, int bufferSizeIndex) {
    this.bufferSizeIndex[d] = bufferSizeIndex;
    }
    }

    //audio utils :

    package Voice.Commander.Sounds.Settings;

    import java.io.InputStream;
    import javax.sound.sampled.*;

    import static Voice.Commander.Sounds.Settings.Constants.*;

    public class AudioUtils {

    private static final float[] netSampleRate={
    1.0f, // nothing
    44100.0f, // CD
    22050.0f, // FM
    8000.0f, // Telephone
    8000.0f // GSM
    };

    public static long bytes2millis(long bytes, AudioFormat format) {
    return (long)
    (bytes/format.getFrameRate()*1000/format.getFrameSize());
    }

    public static long millis2bytes(long ms, AudioFormat format) {
    return (long) (ms*format.getFrameRate()/1000*format.getFrameSize());
    }

    public static AudioFormat getLineAudioFormat(int formatCode) {
    return getLineAudioFormat(netSampleRate[formatCode]);
    }

    public static AudioFormat getLineAudioFormat(float sampleRate) {
    return new AudioFormat(
    AudioFormat.Encoding.PCM_SIGNED,
    sampleRate, // sampleRate
    16, // sampleSizeInBits
    1, // channels
    2, // frameSize
    sampleRate, // frameRate
    false); // bigEndian
    }

    public static AudioFormat getNetAudioFormat(int formatCode) throws
    UnsupportedAudioFileException {
    if (formatCode==FORMAT_CODE_CD) {
    return new AudioFormat(
    AudioFormat.Encoding.PCM_SIGNED,
    44100.0f, // sampleRate
    16, // sampleSizeInBits
    1, // channels
    2, // frameSize
    44100.0f, // frameRate
    true); // bigEndian
    }
    else if (formatCode==FORMAT_CODE_FM) {
    return new AudioFormat(
    AudioFormat.Encoding.PCM_SIGNED,
    22050.0f, // sampleRate
    16, // sampleSizeInBits
    1, // channels
    2, // frameSize
    22050.0f, // frameRate
    true); // bigEndian
    }
    else if (formatCode==FORMAT_CODE_TELEPHONE) {
    return new AudioFormat(
    AudioFormat.Encoding.ULAW,
    8000.0f, // sampleRate
    8, // sampleSizeInBits
    1, // channels
    1, // frameSize
    8000.0f, // frameRate
    false); // bigEndian
    }
    else if (formatCode==FORMAT_CODE_GSM) {
    /*
    try {
    Class.forName("org.tritonus.share.sampled.Encodings");
    } catch (ClassNotFoundException cnfe) {
    throw new RuntimeException("Tritonus shared classes not properly
    installed!");
    }
    return new AudioFormat(
    org.tritonus.share.sampled.Encodings.getEncoding("GSM0610"),
    8000.0F, // sampleRate
    -1, // sampleSizeInBits
    1, // channels
    33, // frameSize
    50.0F, // frameRate
    false); // bigEndian
    */
    return new AudioFormat(
    new AudioFormat.Encoding("GSM0610"),
    8000.0F, // sampleRate
    -1, // sampleSizeInBits
    1, // channels
    33, // frameSize
    50.0F, // frameRate
    false); // bigEndian
    }
    throw new RuntimeException("Wrong format code!");
    }


    public static AudioInputStream createNetAudioInputStream(
    int formatCode, InputStream stream) {
    try
    {
    AudioFormat format = getNetAudioFormat(formatCode);
    return new AudioInputStream(stream, format,
    AudioSystem.NOT_SPECIFIED);
    }
    catch (UnsupportedAudioFileException e)
    {
    System.out.println(e);
    return null;
    }
    }


    public static int getFormatCode(AudioFormat format) {
    AudioFormat.Encoding encoding = format.getEncoding();
    // very simple check...
    if (encoding.equals(AudioFormat.Encoding.PCM_SIGNED)) {
    if (format.getSampleRate()==44100.0f) {
    return FORMAT_CODE_CD;
    } else {
    return FORMAT_CODE_FM;
    }
    }
    if (encoding.equals(AudioFormat.Encoding.ULAW)) {
    return FORMAT_CODE_TELEPHONE;
    }
    if (encoding.toString().equals("GSM0610")) {
    return FORMAT_CODE_GSM;
    }
    throw new RuntimeException("Wrong Format");
    }

    }

    //constants.java
    package Voice.Commander.Sounds.Settings;


    class Constants {
    public static final int DIR_MIC = 0;
    public static final int DIR_SPK = 1;

    public static boolean DEBUG = true;
    public static boolean VERBOSE = true;

    public static final int FORMAT_CODE_CD=1;
    public static final int FORMAT_CODE_FM=2;
    public static final int FORMAT_CODE_TELEPHONE=3;
    public static final int FORMAT_CODE_GSM=4;

    public static final String[] FORMAT_NAMES={
    "Cell phone GSM (13.2KBit/s - Modem)",
    "Telephone ulaw (64KBit/s - ISDN)",
    "FM quality mono (352.8KBit/s - ADSL)",
    "CD quality mono (705.6KBit/s - LAN)"
    };

    public static final int[] FORMAT_CODES={
    FORMAT_CODE_GSM,
    FORMAT_CODE_TELEPHONE,
    FORMAT_CODE_FM,
    FORMAT_CODE_CD
    };

    public static final int[] BUFFER_SIZE_MILLIS = {
    30, 40, 50, 70, 85, 100, 130, 150, 180, 220, 400
    };
    public static final String[] BUFFER_SIZE_MILLIS_STR = {
    "30", "40", "50", "70", "85", "100", "130", "150", "180", "220",
    "400"
    };
    public static final int BUFFER_SIZE_INDEX_DEFAULT = 2;


    public static final String CONNECTION_PROPERTY = "CONNECTION";
    public static final String AUDIO_PROPERTY = "AUDIO";

    public static final int PROTOCOL_MAGIC = 0x43484154;
    public static final int PROTOCOL_VERSION = 1;
    public static final int PROTOCOL_ACK = 1001;
    public static final int PROTOCOL_ERROR = 1002;

    // Socket options
    public static final boolean TCP_NODELAY = false;
    // -1 means do not set the value
    public static final int TCP_RECEIVE_BUFFER_SIZE = 1024;
    public static final int TCP_SEND_BUFFER_SIZE = 1024;

    public static final int CONNECTION_TYPE_TCP = 1;
    public static final int CONNECTION_TYPE_UDP = 2;

    public static final int[] CONNECTION_TYPES =
    {
    CONNECTION_TYPE_TCP,
    CONNECTION_TYPE_UDP
    };

    public static final String[] CONNECTION_TYPE_NAMES =
    {
    "TCP (for LAN)",
    "UDP (for WAN)"
    };

    public static final int DEFAULT_PORT = 8765;
    public static final int DEFAULT_CONNECTION_TYPE =
    CONNECTION_TYPE_TCP;
    public static final int DEFAULT_FORMAT_CODE =
    FORMAT_CODE_TELEPHONE;

    public static void out(String s) {
    //wSystem.out.println(s);
    }
    }
    , Jan 15, 2007
    #16
  17. wrote:
    > I was using mixer but port is better solution ;


    Next time you feel so excited about solving a problem
    that you are inspired to post over *1000* lines of it to
    the group, please consider ..not doing the last part.
    A simple link* to the code would probably do, for
    most people that might be interested.

    * There are a lot of free sites.

    Andrew T.
    Andrew Thompson, Jan 15, 2007
    #17
  18. Guest

    90% of your posts in this topic are useless..! :)

    But of course thanks a lot to read me :p
    , Feb 1, 2007
    #18
  19. On Thu, 01 Feb 2007 06:28:01 -0800, <> wrote:

    > 90% of your posts in this topic are useless..! :)
    >
    > But of course thanks a lot to read me :p


    Who are you addressing this to?

    --
    Randolf Richardson -
    The Lumber Cartel, local 42 (Canadian branch)
    http://www.lumbercartel.ca/
    Randolf Richardson, Feb 2, 2007
    #19
  20. Guest

    On 2 fév, 03:57, "Randolf Richardson" <>
    wrote:
    > On Thu, 01 Feb 2007 06:28:01 -0800, <> wrote:
    > > 90% of your posts in this topic are useless..! :)

    >
    > > But of course thanks a lot to read me :p

    >
    > Who are you addressing this to?
    >
    > --
    > Randolf Richardson -
    > The Lumber Cartel, local 42 (Canadian branch)http://www.lumbercartel.ca/


    to andrew thomson maybe
    , Feb 2, 2007
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Doug Miller
    Replies:
    0
    Views:
    664
    Doug Miller
    Sep 8, 2004
  2. Mike
    Replies:
    4
    Views:
    1,532
  3. Nomak
    Replies:
    1
    Views:
    4,197
    Phil Staite
    Dec 25, 2004
  4. Luc The Perverse

    Sound Quality In Sound API

    Luc The Perverse, Oct 30, 2005, in forum: Java
    Replies:
    4
    Views:
    1,485
    Andrew Thompson
    Oct 31, 2005
  5. Replies:
    0
    Views:
    505
Loading...

Share This Page