List of usage examples for javax.sound.sampled Clip open
void open(AudioInputStream stream) throws LineUnavailableException, IOException;
From source file:de.tor.tribes.ui.windows.ClockFrame.java
public synchronized void playSound(String pSound) { Clip clip = null; AudioClip ac = null;/*from w w w . j ava 2 s. c om*/ try { if (org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS) { clip = AudioSystem.getClip(); BufferedInputStream bin = new BufferedInputStream( ClockFrame.class.getResourceAsStream("/res/" + pSound + ".wav")); AudioInputStream inputStream = AudioSystem.getAudioInputStream(bin); clip.open(inputStream); clip.start(); } else { ac = Applet.newAudioClip(ClockFrame.class.getResource("/res/" + pSound + ".wav")); ac.play(); } } catch (Exception e) { logger.error("Failed to play sound", e); } try { Thread.sleep(2500); } catch (Exception ignored) { } try { if (clip != null) { clip.stop(); clip.flush(); clip = null; } if (ac != null) { ac.stop(); ac = null; } } catch (Exception ignored) { } }
From source file:io.github.jeremgamer.editor.panels.MusicFrame.java
public MusicFrame(JFrame frame, final GeneralSave gs) { ArrayList<BufferedImage> icons = new ArrayList<BufferedImage>(); try {//ww w . ja v a2s. c om icons.add(ImageIO.read(ImageGetter.class.getResource("icon16.png"))); icons.add(ImageIO.read(ImageGetter.class.getResource("icon32.png"))); icons.add(ImageIO.read(ImageGetter.class.getResource("icon64.png"))); icons.add(ImageIO.read(ImageGetter.class.getResource("icon128.png"))); } catch (IOException e1) { e1.printStackTrace(); } this.setIconImages((List<? extends Image>) icons); this.setTitle("Musique"); this.setSize(new Dimension(300, 225)); this.addWindowListener(new WindowListener() { @Override public void windowActivated(WindowEvent event) { } @Override public void windowClosed(WindowEvent event) { } @Override public void windowClosing(WindowEvent event) { try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } if (clip != null) { clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void windowDeactivated(WindowEvent event) { } @Override public void windowDeiconified(WindowEvent event) { } @Override public void windowIconified(WindowEvent event) { } @Override public void windowOpened(WindowEvent event) { } }); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS)); this.setModal(true); this.setLocationRelativeTo(frame); JPanel properties = new JPanel(); properties.setBorder(BorderFactory.createTitledBorder("Lecture")); ButtonGroup bg = new ButtonGroup(); bg.add(one); bg.add(loop); one.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent event) { JRadioButton rb = (JRadioButton) event.getSource(); if (rb.isSelected()) { gs.set("music.reading", 0); try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } if (clip != null) { if (clip.isRunning()) clip.loop(0); } } } }); loop.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent event) { JRadioButton rb = (JRadioButton) event.getSource(); if (rb.isSelected()) { gs.set("music.reading", 1); try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } if (clip != null) { if (clip.isRunning()) clip.loop(Clip.LOOP_CONTINUOUSLY); } } } }); properties.add(one); properties.add(loop); if (gs.getInt("music.reading") == 0) { one.setSelected(true); } else { loop.setSelected(true); } volume.setMaximum(100); volume.setMinimum(0); volume.setValue(30); volume.setPaintTicks(true); volume.setPaintLabels(true); volume.setMinorTickSpacing(10); volume.setMajorTickSpacing(20); volume.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent event) { JSlider slider = (JSlider) event.getSource(); double value = slider.getValue(); gain = value / 100; dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0); if (clip != null) gainControl.setValue(dB); gs.set("music.volume", (int) value); } }); volume.setValue(gs.getInt("music.volume")); properties.add(volume); properties.setPreferredSize(new Dimension(300, 125)); content.add(properties); JPanel browsePanel = new JPanel(); browsePanel.setBorder(BorderFactory.createTitledBorder("")); JButton browse = new JButton("Parcourir..."); if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) { preview.setEnabled(false); browse.setText(""); try { browse.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png")))); } catch (IOException e) { e.printStackTrace(); } } browse.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JButton button = (JButton) event.getSource(); if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) { if (clip != null) { clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } name.setText(""); preview.setEnabled(false); button.setText("Parcourir..."); button.setIcon(null); new File("projects/" + Editor.getProjectName() + "/music.wav").delete(); gs.set("music.name", ""); } else { String path = null; JFileChooser chooser = new JFileChooser(Editor.lastPath); FileNameExtensionFilter filter = new FileNameExtensionFilter("Audio (WAV)", "wav"); chooser.setFileFilter(filter); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = chooser.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { path = chooser.getSelectedFile().getAbsolutePath(); Editor.lastPath = chooser.getSelectedFile().getParent(); copyMusic(new File(path)); button.setText(""); try { button.setIcon( new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png")))); } catch (IOException e) { e.printStackTrace(); } gs.set("music.name", new File(path).getName()); try { gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e) { e.printStackTrace(); } name.setText(new File(path).getName()); preview.setEnabled(true); } } } }); if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) { preview.setEnabled(true); } else { preview.setEnabled(false); } preview.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JToggleButton tb = (JToggleButton) event.getSource(); if (tb.isSelected()) { try { audioStream = AudioSystem.getAudioInputStream( new File("projects/" + Editor.getProjectName() + "/music.wav")); format = audioStream.getFormat(); info = new DataLine.Info(Clip.class, format); clip = (Clip) AudioSystem.getLine(info); clip.open(audioStream); clip.start(); gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(dB); if (loop.isSelected()) { clip.loop(Clip.LOOP_CONTINUOUSLY); } else { clip.loop(0); } clip.addLineListener(new LineListener() { @Override public void update(LineEvent event) { Clip clip = (Clip) event.getSource(); if (!clip.isRunning()) { preview.setSelected(false); clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }); } catch (Exception exc) { exc.printStackTrace(); } } else { clip.stop(); clip.close(); try { audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }); JPanel buttons = new JPanel(); buttons.setLayout(new BorderLayout()); buttons.add(browse, BorderLayout.WEST); buttons.add(preview, BorderLayout.EAST); browsePanel.setLayout(new BorderLayout()); browsePanel.add(buttons, BorderLayout.NORTH); browsePanel.add(name, BorderLayout.SOUTH); name.setPreferredSize(new Dimension(280, 25)); name.setText(gs.getString("music.name")); content.add(browsePanel); this.setContentPane(content); this.setVisible(true); }
From source file:org.yccheok.jstock.chat.Utils.java
public static void playSound(final Sound sound) { if (sounds.size() == 0) { for (Sound s : Sound.values()) { AudioInputStream stream = null; Clip clip = null; try { switch (s) { case ALERT: stream = AudioSystem .getAudioInputStream(new File(Utils.getSoundsDirectory() + "alert.wav")); break; case LOGIN: stream = AudioSystem .getAudioInputStream(new File(Utils.getSoundsDirectory() + "login.wav")); break; case LOGOUT: stream = AudioSystem .getAudioInputStream(new File(Utils.getSoundsDirectory() + "logout.wav")); break; case RECEIVE: stream = AudioSystem .getAudioInputStream(new File(Utils.getSoundsDirectory() + "receive.wav")); break; case SEND: stream = AudioSystem.getAudioInputStream(new File(Utils.getSoundsDirectory() + "send.wav")); break; default: throw new java.lang.IllegalArgumentException("Missing case " + sound); }/* w w w. j ava2 s . co m*/ // At present, ALAW and ULAW encodings must be converted // to PCM_SIGNED before it can be played AudioFormat format = stream.getFormat(); if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) { format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2, format.getFrameRate(), true); // big endian stream = AudioSystem.getAudioInputStream(format, stream); } // Create the clip DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(), ((int) stream.getFrameLength() * format.getFrameSize())); clip = (Clip) AudioSystem.getLine(info); // This method does not return until the audio file is completely loaded clip.open(stream); clip.drain(); sounds.put(s, clip); } catch (MalformedURLException e) { log.error(null, e); } catch (IOException e) { log.error(null, e); } catch (LineUnavailableException e) { log.error(null, e); } catch (UnsupportedAudioFileException e) { log.error(null, e); } finally { } } } soundPool.execute(new Runnable() { @Override public void run() { Clip clip = sounds.get(sound); if (clip == null) { return; } clip.stop(); clip.flush(); clip.setFramePosition(0); clip.loop(0); // Wait for the sound to finish. //while (clip.isRunning()) { // try { // Thread.sleep(1); // } catch (InterruptedException ex) { // log.error(null, ex); // } //} } }); }
From source file:gui.EventReader.java
@Override public void run() { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build(); HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); //HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet( //"https://api.guildwars2.com/v1/events.json?world_id=" "http://gw2eventer.sourceforge.net/api/events.php?world_id=" + this.worldID); HttpResponse response;//from w w w.j a va 2s. c om String line = ""; String out = ""; while (!isInterrupted()) { try { this.labelWorking.setText(this.workingString); try { response = client.execute(request); if (response.getStatusLine().toString().contains("200")) { BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8"))); line = ""; out = ""; while ((line = rd.readLine()) != null) { out = out + line; } } else { // http error request.releaseConnection(); this.refreshSelector.setEnabled(false); this.workingButton.setEnabled(false); this.jComboBoxLanguage.setEnabled(false); this.labelWorking.setText("connection error. retrying in... 10."); this.labelWorking.setVisible(true); Thread.sleep(10000); continue; } } catch (IOException | IllegalStateException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); request.releaseConnection(); this.refreshSelector.setEnabled(false); this.workingButton.setEnabled(false); this.jComboBoxLanguage.setEnabled(false); this.labelWorking.setText("connection error. retrying in... 10."); this.labelWorking.setVisible(true); Thread.sleep(10000); continue; //this.interrupt(); } request.releaseConnection(); JSONParser parser = new JSONParser(); Object obj; this.result.clear(); HashMap mehrfachEvents = new HashMap(); playSoundsList.clear(); this.overlayGui.clearActive(); String toolTip; try { obj = parser.parse(out); for (int i = 0; i < this.eventLabels.size(); i++) { JLabel iter = (JLabel) this.eventLabels.get(i); iter.setEnabled(false); iter.setForeground(Color.green); } for (Iterator iterator = ((JSONObject) obj).values().iterator(); iterator.hasNext();) { JSONArray arrayNew = (JSONArray) iterator.next(); for (int i = 0; i < arrayNew.size(); i++) { JSONObject obj2 = (JSONObject) arrayNew.get(i); if (obj2.get("event_id") != null) { String event = (String) obj2.get("event_id"); if (this.events.containsKey(event)) { //System.out.println("debug: " + event + "\n"); this.result.add(obj2.get("event_id")); int indexEvent = Integer.parseInt(((String[]) this.events.get(event))[0]); String eventPercent = ((String[]) this.events.get(event))[1]; String eventWav = ((String[]) this.events.get(event))[2]; String eventName = ((String[]) this.events.get(event))[3]; JLabel activeLabel = (JLabel) this.eventLabels.get(indexEvent - 1); JLabel activeLabelTimer = (JLabel) this.eventLabelsTimer.get(indexEvent - 1); int activeLabelInt = indexEvent - 1; String tmpEventName = eventPercent.substring(0, 1); Date dateNow = new Date(); long stampNow = dateNow.getTime(); if (this.timerStamps[activeLabelInt] != null) { long oldTimestamp = this.timerStamps[activeLabelInt].getTime(); long minsdiff = ((stampNow - oldTimestamp) / 1000 / 60); if (minsdiff >= 30) { activeLabelTimer.setEnabled(true); } else { activeLabelTimer.setEnabled(false); } if (minsdiff >= 60) { activeLabelTimer.setForeground(Color.red); } else { activeLabelTimer.setForeground(Color.green); } activeLabelTimer.setText(minsdiff + " mins (B)"); } /* if (activeLabel != null) { if (activeLabel.getToolTipText() != null) { if (activeLabel.getToolTipText().equals("")) { // null pointer?? activeLabel.setToolTipText((String) this.allEvents.get(obj2.get("event_id"))); } } }*/ if (obj2.get("state").equals("Active")) { activeLabel.setEnabled(true); //activeLabel.setToolTipText((String) this.allEvents.get(obj2.get("event_id"))); toolTip = activeLabel.getToolTipText(); if (toolTip != null) { if (toolTip.length() > 35) { toolTip = toolTip.substring(0, 35) + "..."; } } else { toolTip = ""; } if (tmpEventName.equals("B")) { this.markedBs[activeLabelInt] = true; activeLabelTimer.setVisible(false); this.timerStamps[activeLabelInt] = null; if (this.eventPlaySounds[activeLabelInt][2]) { if (!this.overlayGui.containsActiveB(eventName)) { this.overlayGui.addActiveB(eventName, "yellow", activeLabelInt); } } else { if (!this.overlayGui.containsActiveB(eventName)) { this.overlayGui.addActiveB(eventName, "green", activeLabelInt); } } } else { if (this.eventPlaySounds[activeLabelInt][2]) { if (!this.overlayGui.containsActivePre(eventName)) { this.overlayGui.addActivePreEvent(eventName, "yellow", activeLabelInt); } } else { if (!this.overlayGui.containsActivePre(eventName)) { this.overlayGui.addActivePreEvent(eventName, "green", activeLabelInt); } } } //activeLabel.setSize(100, activeLabel.getSize().height); //activeLabel.setText(eventPercent); URL url = this.getClass().getClassLoader() .getResource("media/sounds/" + eventWav + ".wav"); if (!playSoundsList.containsKey(url)) { if (!this.eventPlaySounds[activeLabelInt][2]) { if (tmpEventName.equals("B")) { if (this.eventPlaySounds[activeLabelInt][1]) { playSoundsList.put(url, activeLabel); } } else { if (this.eventPlaySounds[activeLabelInt][0]) { playSoundsList.put(url, activeLabel); } } } else { activeLabel.setForeground(Color.YELLOW); } } if (mehrfachEvents.containsKey(activeLabel)) { ((ArrayList) mehrfachEvents.get(activeLabel)).add(tmpEventName); } else { ArrayList tmpListe = new ArrayList(); tmpListe.add(tmpEventName); mehrfachEvents.put(activeLabel, tmpListe); } } else { if (tmpEventName.equals("B")) { if (this.markedBs[activeLabelInt]) { this.timerStamps[activeLabelInt] = dateNow; this.markedBs[activeLabelInt] = false; activeLabelTimer.setVisible(true); activeLabelTimer.setText("0 mins (B)"); } } } } } } } Iterator it = mehrfachEvents.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); JLabel label = (JLabel) pairs.getKey(); ArrayList liste = (ArrayList) pairs.getValue(); String outString = null; Collections.sort(liste, new Comparator<String>() { public int compare(String f1, String f2) { return -f1.toString().compareTo(f2.toString()); } }); for (int i = 0; i < liste.size(); i++) { if (outString == null) { outString = (String) liste.get(i); } else { outString += ", " + (String) liste.get(i); } } label.setText(outString); it.remove(); } this.labelServer.setOpaque(true); this.labelServer.setOpaque(false); this.labelServer.setEnabled(false); this.labelServer.setText(""); this.labelServer.setText(this.worldName); this.labelWorking.setVisible(false); this.refreshSelector.setEnabled(true); this.workingButton.setEnabled(true); this.jComboBoxLanguage.setEnabled(true); this.overlayGui.renderActive(); if (playSounds) { this.playThread = new Thread() { @Override public void run() { Iterator it = playSoundsList.entrySet().iterator(); while (it.hasNext() && !isInterrupted()) { AudioInputStream audioIn; Map.Entry pairs = (Map.Entry) it.next(); JLabel label = (JLabel) pairs.getValue(); try { playSoundsCurrent = (URL) pairs.getKey(); audioIn = AudioSystem.getAudioInputStream(playSoundsCurrent); Clip clip = null; String tmp = label.getText(); try { //label.setText(">" + tmp); //label.setText("<HTML><U>" + tmp + "<U><HTML>"); label.setForeground(Color.red); //Font font = label.getFont(); //Map attributes = font.getAttributes(); //attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); //label.setFont(font.deriveFont(attributes)); clip = AudioSystem.getClip(); clip.open(audioIn); clip.start(); } catch (LineUnavailableException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); } finally { try { audioIn.close(); } catch (IOException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); } } try { Thread.sleep(2000); //label.setText(tmp); label.setForeground(Color.green); } catch (InterruptedException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); this.interrupt(); //?? } } catch (UnsupportedAudioFileException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); } it.remove(); } } }; this.playThread.start(); this.playThread.join(); } } catch (ParseException ex) { Logger.getLogger(ApiManager.class.getName()).log(Level.SEVERE, null, ex); this.refreshSelector.setEnabled(false); this.workingButton.setEnabled(false); this.jComboBoxLanguage.setEnabled(false); this.labelWorking.setText("connection error. retrying in... 10."); this.labelWorking.setVisible(true); Thread.sleep(10000); continue; } if (this.autoRefresh) { Thread.sleep(this.sleepTime * 1000); } else { this.interrupt(); } } catch (InterruptedException ex) { Logger.getLogger(ApiManager.class.getName()).log(Level.SEVERE, null, ex); this.interrupt(); } } }
From source file:com.marginallyclever.makelangelo.MainGUI.java
private void PlaySound(String url) { if (url.isEmpty()) return;// w w w .j av a 2s .co m try { Clip clip = AudioSystem.getClip(); BufferedInputStream x = new BufferedInputStream(new FileInputStream(url)); AudioInputStream inputStream = AudioSystem.getAudioInputStream(x); clip.open(inputStream); clip.start(); } catch (Exception e) { e.printStackTrace(); System.err.println(e.getMessage()); } }
From source file:org.yccheok.jstock.gui.Utils.java
public static void playAlertSound() { new Thread(new Runnable() { @Override/*from w w w . j av a2s .c om*/ public void run() { try { Clip clip = AudioSystem.getClip(); clip.addLineListener(new LineListener() { @Override public void update(LineEvent event) { if (event.getType() == LineEvent.Type.STOP) { event.getLine().close(); } } }); final InputStream audioSrc = Utils.class.getResourceAsStream("/assets/sounds/doorbell.wav"); // http://stackoverflow.com/questions/5529754/java-io-ioexception-mark-reset-not-supported // Add buffer for mark/reset support. final InputStream bufferedIn = new BufferedInputStream(audioSrc); AudioInputStream inputStream = AudioSystem.getAudioInputStream(bufferedIn); clip.open(inputStream); clip.start(); } catch (Exception e) { log.error(null, e); } } }).start(); }