Example usage for javax.sound.sampled Clip start

List of usage examples for javax.sound.sampled Clip start

Introduction

In this page you can find the example usage for javax.sound.sampled Clip start.

Prototype

void start();

Source Link

Document

Allows a line to engage in data I/O.

Usage

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 ww  .  j a v a 2 s . 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: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.  ja v  a 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;/*  ww w. jav  a  2s  .  c o 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. ja  v a 2s  . 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();
}