Example usage for javax.sound.sampled Clip addLineListener

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

Introduction

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

Prototype

void addLineListener(LineListener listener);

Source Link

Document

Adds a listener to this line.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DataLine.Info info = null;//from w  w w  .ja  va 2  s  .c o  m
    Clip clip = (Clip) AudioSystem.getLine(info);

    clip.addLineListener(new LineListener() {
        public void update(LineEvent evt) {
            if (evt.getType() == LineEvent.Type.STOP) {
            }
        }
    });
}

From source file:ClipTest.java

public static void main(String[] args) throws Exception {

    // specify the sound to play
    // (assuming the sound can be played by the audio system)
    File soundFile = new File("../sounds/voice.wav");
    AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

    // load the sound into memory (a Clip)
    DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
    Clip clip = (Clip) AudioSystem.getLine(info);
    clip.open(sound);/*  w ww .  ja  v  a 2s.  co m*/

    // due to bug in Java Sound, explicitly exit the VM when
    // the sound has stopped.
    clip.addLineListener(new LineListener() {
        public void update(LineEvent event) {
            if (event.getType() == LineEvent.Type.STOP) {
                event.getLine().close();
                System.exit(0);
            }
        }
    });

    // play the sound clip
    clip.start();
}

From source file:SimpleSoundPlayer.java

public boolean loadSound(Object object) {
    duration = 0.0;//from   w w w .  j  a  v  a2s  .  c  om

    currentName = ((File) object).getName();
    try {
        currentSound = AudioSystem.getAudioInputStream((File) object);
    } catch (Exception e1) {
        try {
            FileInputStream is = new FileInputStream((File) object);
            currentSound = new BufferedInputStream(is, 1024);
        } catch (Exception e3) {
            e3.printStackTrace();
            currentSound = null;
            return false;
        }
        // }
    }

    // user pressed stop or changed tabs while loading
    if (sequencer == null) {
        currentSound = null;
        return false;
    }

    if (currentSound instanceof AudioInputStream) {
        try {
            AudioInputStream stream = (AudioInputStream) currentSound;
            AudioFormat format = stream.getFormat();

            /**
             * we can't yet open the device for ALAW/ULAW playback, convert
             * ALAW/ULAW to PCM
             */

            if ((format.getEncoding() == AudioFormat.Encoding.ULAW)
                    || (format.getEncoding() == AudioFormat.Encoding.ALAW)) {
                AudioFormat tmp = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(),
                        format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2,
                        format.getFrameRate(), true);
                stream = AudioSystem.getAudioInputStream(tmp, stream);
                format = tmp;
            }
            DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
                    ((int) stream.getFrameLength() * format.getFrameSize()));

            Clip clip = (Clip) AudioSystem.getLine(info);
            clip.addLineListener(this);
            clip.open(stream);
            currentSound = clip;
            // seekSlider.setMaximum((int) stream.getFrameLength());
        } catch (Exception ex) {
            ex.printStackTrace();
            currentSound = null;
            return false;
        }
    } else if (currentSound instanceof Sequence || currentSound instanceof BufferedInputStream) {
        try {
            sequencer.open();
            if (currentSound instanceof Sequence) {
                sequencer.setSequence((Sequence) currentSound);
            } else {
                sequencer.setSequence((BufferedInputStream) currentSound);
            }

        } catch (InvalidMidiDataException imde) {
            System.out.println("Unsupported audio file.");
            currentSound = null;
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            currentSound = null;
            return false;
        }
    }

    duration = getDuration();

    return true;
}

From source file:fr.ritaly.dungeonmaster.audio.SoundSystem.java

private void play(final double angle, final double distance, final AudioClip clip) {

    if (clip == null) {
        throw new IllegalArgumentException("The given audio clip is null");
    }// www.  j  a  va2  s . c  o m
    if (!isInitialized()) {
        // On ne lve pas d'erreur pour les tests unitaires
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("Submitting new task ...");
    }

    executorService.execute(new Runnable() {
        @Override
        public void run() {
            final Sound sound = sounds.get(clip.getSound());

            if (sound == null) {
                throw new IllegalArgumentException("Unsupported sound <" + clip + ">");
            }

            try {
                final Clip clip2 = (Clip) AudioSystem
                        .getLine(new DataLine.Info(Clip.class, sound.getAudioFormat()));

                clip2.addLineListener(new LineListener() {
                    @Override
                    public void update(LineEvent event) {
                        if (event.getType().equals(LineEvent.Type.STOP)) {
                            clip2.close();
                        }
                    }
                });
                clip2.open(sound.getAudioFormat(), sound.getData(), 0, sound.getData().length);

                final DecimalFormat decimalFormat = new DecimalFormat("###.#");

                // Pan dans [-1, +1]
                final FloatControl pan = (FloatControl) clip2.getControl(FloatControl.Type.PAN);

                if (!Double.isNaN(angle)) {

                    final float p = (float) Math.sin(angle);

                    if ((0 <= angle) && (angle <= Math.PI)) {
                        // Son sur la gauche, pan positif
                        pan.setValue(p);
                    } else {
                        // Son sur la droite, pan ngatif
                        pan.setValue(p);
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("Angle = " + decimalFormat.format((angle / Math.PI) * 180) + " / Pan = "
                                + decimalFormat.format(p * 100));
                    }
                } else {
                    pan.setValue(0);
                }

                final double attenuation = Utils.attenuation(distance);

                if (log.isDebugEnabled()) {
                    log.debug("Distance = " + distance + " / Attenuation = "
                            + decimalFormat.format((attenuation * 100)) + "%");
                }

                if (distance != 0) {
                    // Gain dans [-30, 0]
                    final FloatControl gain = (FloatControl) clip2.getControl(FloatControl.Type.MASTER_GAIN);

                    gain.setValue((float) attenuation * -30);
                }

                clip2.loop(0);
            } catch (LineUnavailableException e) {
                throw new RuntimeException(e);
            }
        }
    });

    if (log.isDebugEnabled()) {
        log.debug("Task submitted");
    }
}

From source file:io.github.jeremgamer.editor.panels.MusicFrame.java

public MusicFrame(JFrame frame, final GeneralSave gs) {

    ArrayList<BufferedImage> icons = new ArrayList<BufferedImage>();
    try {//  www  . j av 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: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./* www  . j av  a2 s . c om*/
 * 
 * @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:org.yccheok.jstock.gui.Utils.java

public static void playAlertSound() {
    new Thread(new Runnable() {
        @Override/*from   w  ww.j  a va2s. 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();
}