List of usage examples for javax.sound.sampled AudioSystem getClip
public static Clip getClip() throws LineUnavailableException
From source file:org.openhab.io.multimedia.actions.Audio.java
@ActionDoc(text = "plays a sound from the sounds folder") static public void playSound( @ParamDoc(name = "filename", text = "the filename with extension") String filename) { try {/*ww w . j av a 2 s .com*/ InputStream is = new FileInputStream(SOUND_DIR + File.separator + filename); if (filename.toLowerCase().endsWith(".mp3")) { Player player = new Player(is); playInThread(player); } else { AudioInputStream ais = AudioSystem.getAudioInputStream(is); Clip clip = AudioSystem.getClip(); clip.open(ais); playInThread(clip); } } catch (FileNotFoundException e) { logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() }); } catch (JavaLayerException e) { logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() }); } catch (UnsupportedAudioFileException e) { logger.error("Format of sound file '{}' is not supported: {}", new String[] { filename, e.getMessage() }); } catch (IOException e) { logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() }); } catch (LineUnavailableException e) { logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() }); } }
From source file:com.jostrobin.battleships.view.sound.DefaultSoundEffects.java
private void playSound(final String path) { if (enabled) { InputStream is = ClassLoader.getSystemResourceAsStream(path); AudioInputStream audioInputStream = null; try {/*from w w w . java 2s. co m*/ audioInputStream = AudioSystem.getAudioInputStream(is); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); while (clip.isRunning()) { Thread.sleep(10); } } catch (Exception e) { logger.warn("Could not play sound effect", e); } finally { IOUtils.closeSilently(is, audioInputStream); } } }
From source file:de.tor.tribes.util.ClipboardWatch.java
private synchronized void playNotification() { if (!Boolean.parseBoolean(GlobalOptions.getProperty("clipboard.notification"))) { return;//from www . j a v a 2 s.c o m } Timer t = new Timer("ClipboardNotification", true); t.schedule(new TimerTask() { @Override public void run() { if (clip != null) {//reset clip clip.stop(); clip.setMicrosecondPosition(0); } if (ac != null) { ac.stop(); } try { if (org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS) { if (clip == null) { clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem .getAudioInputStream(ClockFrame.class.getResourceAsStream("/res/Ding.wav")); clip.open(inputStream); } clip.start(); } else { if (ac == null) { ac = Applet.newAudioClip(ClockFrame.class.getResource("/res/Ding.wav")); } ac.play(); } } catch (Exception e) { logger.error("Failed to play notification", e); } } }, 0); }
From source file:patientview.HistoryJFrame.java
/** * Creates new form HistoryJFrame//www. j a v a 2s .c o m */ public HistoryJFrame(int bedNum, int time, Patients patients) { initComponents(); //set window in the center of the screen //Get the size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); //Determine the new location of the window int w = this.getSize().width; int h = this.getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; //Move the window this.setLocation(x, y); //Load click sound try { AudioInputStream audioInputStream = AudioSystem .getAudioInputStream(new File("sounds/click.wav").getAbsoluteFile()); click = AudioSystem.getClip(); click.open(audioInputStream); } catch (Exception ex) { System.out.println(ex.toString()); } //Get patient this.patients = patients; this.bedNum = bedNum; thisPatient = patients.getPatient(bedNum); //Set background colour this.getContentPane().setBackground(new Color(240, 240, 240)); //fill titles wardNumField.setText("W001"); bedNumField.setText(String.valueOf(bedNum)); checkBoxes = new ArrayList<JCheckBox>() { { add(jCheckBox1); add(jCheckBox2); add(jCheckBox3); add(jCheckBox4); add(jCheckBox5); add(jCheckBox6); } }; genGraph(getGraphCode()); //set timer timerCSeconds = time; if (timer == null) { timer = new Timer(10, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // do it every 10 msecond Calendar cal = Calendar.getInstance(); cal.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); jLabel_systemTime.setText(sdf.format(cal.getTime())); // do it every 5 seconds if (timerCSeconds % 500 == 0) { //genGraph(getGraphCode()); //only useful for dispalying data up until the current moment } timerCSeconds++; } }); } if (timer.isRunning() == false) { timer.start(); } }
From source file:de.tor.tribes.ui.windows.ClockFrame.java
public synchronized void playSound(String pSound) { Clip clip = null;//from ww w . ja va 2 s . com AudioClip ac = null; 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:com.marginallyclever.makelangelo.MainGUI.java
private void PlaySound(String url) { if (url.isEmpty()) return;//from w w w . j a v a 2s.c om 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: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 ww w . j ava2s.co m 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.xyphos.vmtgen.GUI.java
private void generateVMT() { if (-1 == lstFiles.getSelectedIndex()) { return;/*from w ww . ja v a2 s . c om*/ } String value = lstFiles.getSelectedValue().toString(); String path = FilenameUtils .separatorsToSystem(FilenameUtils.concat(workPath, FilenameUtils.getBaseName(value) + ".VMT")); File fileVMT = new File(path); try (PrintWriter out = new PrintWriter(fileVMT, "UTF-8")) { value = (0 == cmbShader.getSelectedIndex()) ? txtShader.getText() : cmbShader.getSelectedItem().toString(); // write the shader out.printf("\"%s\"%n{%n", value); writeSpinner(out, nudAlpha, 1F, "$alpha", 4); writeSpinner(out, nudEnvMapContrast, 0F, "$envMapContrast", 3); writeSpinner(out, nudEnvMapContrast, 0F, "$envMapSaturation", 2); writeSpinner(out, nudEnvMapFrame, 0, "$envMapFrame", 3); // write surfaces int index = cmbSurface1.getSelectedIndex(); if (0 != index) { value = (1 == index) ? txtSurface1.getText() : cmbSurface1.getSelectedItem().toString(); writeKeyValue(true, out, "$surfaceProp", value, 3); } index = cmbSurface2.getSelectedIndex(); if (0 != index) { value = (1 == index) ? txtSurface2.getText() : cmbSurface2.getSelectedItem().toString(); writeKeyValue(true, out, "$surfaceProp2", value, 3); } writeKeyValue(!(value = txtKeywords.getText()).isEmpty(), out, "%keywords", value, 3); writeKeyValue(!(value = txtToolTexture.getText()).isEmpty(), out, "%toolTexture", value, 3); writeKeyValue(!(value = txtBaseTexture1.getText()).isEmpty(), out, "$baseTexture", value, 3); writeKeyValue(!(value = txtBaseTexture2.getText()).isEmpty(), out, "$baseTexture2", value, 3); writeKeyValue(!(value = txtDetailTexture.getText()).isEmpty(), out, "$detail", value, 4); writeKeyValue(!(value = txtBumpMap1.getText()).isEmpty(), out, "$bumpMap", value, 3); writeKeyValue(!(value = txtBumpMap2.getText()).isEmpty(), out, "$bumpMap2", value, 3); writeKeyValue(!(value = txtEnvMap.getText()).isEmpty(), out, "$envMap", value, 3); writeKeyValue(!(value = txtEnvMapMask.getText()).isEmpty(), out, "$envMapMask", value, 3); writeKeyValue(!(value = txtNormalMap.getText()).isEmpty(), out, "$normalMap", value, 3); writeKeyValue(!(value = txtDuDvMap.getText()).isEmpty(), out, "$DuDvMap", value, 3); value = "1"; writeKeyValue(chkFlagAdditive.isSelected(), out, "$additive", value, 3); writeKeyValue(chkFlagAlphaTest.isSelected(), out, "$alphaTest", value, 3); writeKeyValue(chkFlagIgnoreZ.isSelected(), out, "$ignoreZ", value, 3); writeKeyValue(chkFlagNoCull.isSelected(), out, "$noCull", value, 4); writeKeyValue(chkFlagNoDecal.isSelected(), out, "$noDecal", value, 3); writeKeyValue(chkFlagNoLOD.isSelected(), out, "$noLOD", value, 3); writeKeyValue(chkFlagPhong.isSelected(), out, "$phong", value, 4); writeKeyValue(chkFlagSelfIllum.isSelected(), out, "$selfIllum", value, 3); writeKeyValue(chkFlagTranslucent.isSelected(), out, "$translucent", value, 3); writeKeyValue(chkFlagVertexAlpha.isSelected(), out, "$vertexAlpha", value, 3); writeKeyValue(chkFlagVertexColor.isSelected(), out, "$vertexColor", value, 3); writeKeyValue(chkCompileClip.isSelected(), out, "%compileClip", value, 3); writeKeyValue(chkCompileDetail.isSelected(), out, "%compileDetail", value, 3); writeKeyValue(chkCompileFog.isSelected(), out, "%compileFog", value, 3); writeKeyValue(chkCompileHint.isSelected(), out, "%compileHint", value, 3); writeKeyValue(chkCompileLadder.isSelected(), out, "%compileLadder", value, 3); writeKeyValue(chkCompileNoDraw.isSelected(), out, "%compileNoDraw", value, 3); writeKeyValue(chkCompileNoLight.isSelected(), out, "%compileNoLight", value, 3); writeKeyValue(chkCompileNonSolid.isSelected(), out, "%compileNonSolid", value, 2); writeKeyValue(chkCompileNpcClip.isSelected(), out, "%compileNpcClip", value, 3); writeKeyValue(chkCompilePassBullets.isSelected(), out, "%compilePassBullets", value, 2); writeKeyValue(chkCompilePlayerClip.isSelected(), out, "%compilePlayerClip", value, 2); writeKeyValue(chkCompilePlayerControlClip.isSelected(), out, "%compilePlayerControlClip", value, 2); writeKeyValue(chkCompileSkip.isSelected(), out, "%compileSkip", value, 3); writeKeyValue(chkCompileSky.isSelected(), out, "%compileSky", value, 3); writeKeyValue(chkCompileTrigger.isSelected(), out, "%compileTrigger", value, 3); // animation code if (animated) { value = nudFrameRate.getValue().toString(); out.printf("%n\t\"proxies\"%n"); out.printf("\t{%n"); out.printf("\t\t\"animatedTexture\"%n"); out.printf("\t\t{%n"); out.printf("\t\t\t\"animatedTextureVar\"\t\t\"$baseTexture\"%n"); out.printf("\t\t\t\"animatedTextureFrameNumVar\"\t\"$frame\"%n"); out.printf("\t\t\t\"animatedTextureFrameRate\" \t\"%s\"%n", value); out.printf("\t\t}%n"); out.printf("\t}%n"); } out.print("}"); out.flush(); try { URL url = this.getClass().getClassLoader().getResource("blip.wav"); AudioInputStream audioIn = AudioSystem.getAudioInputStream(url); clipBlip = AudioSystem.getClip(); clipBlip.open(audioIn); clipBlip.start(); } catch (LineUnavailableException | UnsupportedAudioFileException | IOException ex) { logger.log(Level.SEVERE, null, ex); } } catch (FileNotFoundException | UnsupportedEncodingException ex) { logger.log(Level.SEVERE, null, ex); } }
From source file:ca.sqlpower.dao.SPPersisterListener.java
/** * Does the actual commit when the transaction count reaches 0. This ensures * the persist calls are contained in a transaction if a lone change comes * through. This also allows us to roll back changes if an exception comes * from the server./* w w w .j av a 2s.c o m*/ * * @throws SPPersistenceException */ private void commit() throws SPPersistenceException { logger.debug("commit(): transactionCount = " + transactionCount); if (transactionCount == 1) { try { logger.debug("Calling commit..."); //If nothing actually changed in the transaction do not send //the begin and commit to reduce server traffic. if (objectsToRemove.isEmpty() && persistedObjects.isEmpty() && persistedProperties.isEmpty()) return; target.begin(); commitRemovals(); commitObjects(); commitProperties(); target.commit(); logger.debug("...commit completed."); if (logger.isDebugEnabled()) { try { final Clip clip = AudioSystem.getClip(); clip.open(AudioSystem .getAudioInputStream(getClass().getResource("/sounds/transaction_complete.wav"))); clip.addLineListener(new LineListener() { public void update(LineEvent event) { if (event.getType().equals(LineEvent.Type.STOP)) { logger.debug("Stopping sound"); clip.close(); } } }); clip.start(); } catch (Exception ex) { logger.debug("A transaction committed but we cannot play the commit sound.", ex); } } } catch (Throwable t) { logger.warn("Rolling back due to " + t, t); this.rollback(); if (t instanceof SPPersistenceException) throw (SPPersistenceException) t; if (t instanceof FriendlyRuntimeSPPersistenceException) throw (FriendlyRuntimeSPPersistenceException) t; throw new SPPersistenceException(null, t); } finally { clear(); this.transactionCount = 0; } } else { transactionCount--; } }
From source file:la2launcher.MainFrame.java
public static synchronized void playSound() { new Thread(new Runnable() { // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. public void run() { try { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream( new BufferedInputStream(this.getClass().getResourceAsStream("alert.vaw"))); clip.open(inputStream);//w w w . ja v a 2 s .c o m //clip.start(); } catch (Exception e) { System.err.println(e.getMessage()); } } }).start(); }