
zarmin
|
Réponse acceptée !
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[i]); 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[i] instanceof Port.Info) { Port.Info info = (Port.Info) infos[i]; 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[i] 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); } }
|